#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "pagesource.h"
#include "frmmessagebox.h"

#include <fftw3.h>

#define PI 3.1415927

extern QString etherPortName;
extern int channelMapping[6];

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    layoutSetup();

    cappacket = new CapPacket();
    connect(cappacket, SIGNAL(sigFind(QString,QString,QString,int,int)),this, SLOT(addList(QString,QString,QString,int,int)));
    connect(cappacket,SIGNAL(sigCyOver()),this,SLOT(settempbuff()));
    connect(cappacket, SIGNAL(szbDone()), this, SLOT(szbSlot()));

    udp = new UdpClient();
    connect(udp,SIGNAL(sigUdpMutIsReady()),this,SLOT(triggerPPS()));
    connect(udp,SIGNAL(sigUdpDataShow()),this,SLOT(showDelayText()));

    myDB = new ProjectDB();

    fakePPS = new QTimer();
    pps_count = 0;
    connect(fakePPS, SIGNAL(timeout()), this, SLOT(jsMutWc()));

    captimer_mu = new QTimer();
    dsTimer = new QTimer();
    connect(dsTimer,SIGNAL(timeout()),this,SLOT(slotDs()));
    ysTimer = new QTimer();

    showControlFlag = -1;

    connect(ui->btnFunc1_Error, SIGNAL(clicked(bool)),this, SLOT(btn_func_clicked()));
    connect(ui->btnFunc2_Smv, SIGNAL(clicked(bool)),this, SLOT(btn_func_clicked()));
    connect(ui->btnFunc3, SIGNAL(clicked(bool)),this, SLOT(btn_func_clicked()));
    connect(ui->btnFunc4, SIGNAL(clicked(bool)),this, SLOT(btn_func_clicked()));
    connect(ui->btnFunc5, SIGNAL(clicked(bool)),this, SLOT(btn_func_clicked()));
    connect(ui->btnFunc6, SIGNAL(clicked(bool)),this, SLOT(btn_func_clicked()));

    loadPortConfig();

    packet_analyzer.start("packet_analyzer.exe");
}

void MainWindow::layoutSetup()
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);

    stackedPages = new QStackedWidget();
    stackedPages->setFixedSize(1024,768);

    QHBoxLayout *layoutCentalWidget = new QHBoxLayout;
    layoutCentalWidget->setContentsMargins(0,0,0,0);
    layoutCentalWidget->addWidget(stackedPages);

    ui->mainWidget->setLayout(layoutCentalWidget);

    pageBwjy = new BwjyPage;
    connect(pageBwjy->btnStart, SIGNAL(clicked(bool)), this, SLOT(bwTest()));
    connect(pageBwjy->tabWidget, SIGNAL(currentChanged(int)),this, SLOT(bwjy_pageChanged()));

    connect(pageBwjy->enableUA, SIGNAL(clicked(bool)), this, SLOT(repaintSZB()));
    connect(pageBwjy->enableUB, SIGNAL(clicked(bool)), this, SLOT(repaintSZB()));
    connect(pageBwjy->enableUC, SIGNAL(clicked(bool)), this, SLOT(repaintSZB()));
    connect(pageBwjy->enableIA, SIGNAL(clicked(bool)), this, SLOT(repaintSZB()));
    connect(pageBwjy->enableIB, SIGNAL(clicked(bool)), this, SLOT(repaintSZB()));
    connect(pageBwjy->enableIC, SIGNAL(clicked(bool)), this, SLOT(repaintSZB()));

    pageBwjy->paintArea->installEventFilter(this);

    //QWidget *pageBwjy = new QWidget;
    QWidget *pageProtocol = new QWidget;

    pageLubo = new LuboPage;
    connect(pageLubo->labColor1,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor2,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor3,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor4,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor5,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor6,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor7,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor8,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor9,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor10,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor11,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));
    connect(pageLubo->labColor12,SIGNAL(Clicked(ClickableLabel*)), this, SLOT(showLubo()));

    connect(pageLubo->chkSelectAll,SIGNAL(clicked(bool)),this,SLOT(showLubo()));
    connect(pageLubo->btnLuboData,SIGNAL(clicked(bool)),this,SLOT(slotLuboData()));

    connect(pageLubo->scrllCurve,SIGNAL(valueChanged(int)),this,SLOT(scrllCurveScroll()));
    connect(pageLubo->tSlider,SIGNAL(valueChanged(int)),this,SLOT(tTest()));
    connect(pageLubo->btnStart, SIGNAL(clicked(bool)), this, SLOT(startLubo()));

    pageLubo->paintArea->installEventFilter(this);

    pageErrorTest = new errorTestPage;

    connect(pageErrorTest->btnStart, SIGNAL(clicked(bool)), this, SLOT(startErrorTest()));
    connect(pageErrorTest->btnAnalyzeProtocol, SIGNAL(clicked(bool)), this, SLOT(showAll()));
    connect(pageErrorTest->pageAll->btnPre, SIGNAL(clicked(bool)), this, SLOT(changeShowPage()));
    connect(pageErrorTest->pageAll->btnNxt, SIGNAL(clicked(bool)), this, SLOT(changeShowPage()));
    connect(pageErrorTest->btnBack, SIGNAL(clicked(bool)), this, SLOT(slotBack()));
    connect(pageErrorTest->resultAnalyze->btnSave, SIGNAL(clicked(bool)), this, SLOT(saveWcdata()));

    newSaveCycle = false;

    pageErrorTest->paintArea->installEventFilter(this);

    for(int i=0; i<12; i++)
    {
        pageErrorTest->pageAll->subPages[i]->installEventFilter(this);
    }

    pageAuto = new pageAutoVerify;
    connect(pageAuto->btnTest,SIGNAL(clicked()),this,SLOT(autoJDError()));

    QWidget *pageGoose = new QWidget;

    stackedPages->addWidget(pageErrorTest);
    stackedPages->addWidget(pageBwjy);
    stackedPages->addWidget(pageProtocol);
    stackedPages->addWidget(pageLubo);
    stackedPages->addWidget(pageAuto);
    stackedPages->addWidget(pageGoose);

    pageResult = new resultPage(ui->mainWidget);
    pageResult->hide();
    connect(pageResult->btnFirst,SIGNAL(clicked()),this,SLOT(dataFirst()));
    connect(pageResult->btnPrevious,SIGNAL(clicked()),this,SLOT(dataPrevious()));
    connect(pageResult->btnNext,SIGNAL(clicked()),this,SLOT(dataNext()));
    connect(pageResult->btnLast,SIGNAL(clicked()),this,SLOT(dataLast()));
    connect(pageResult->btnDel,SIGNAL(clicked()),this,SLOT(delWcdata()));
    connect(pageResult->btnDel,SIGNAL(pressed()),this,SLOT(startTimer()));
    connect(pageResult->btnDel,SIGNAL(released()),this,SLOT(stopTimer()));

    delShowtimer = new QTimer();
    connect(delShowtimer, SIGNAL(timeout()),this, SLOT(showDelAllMsg()));

    pageSystem = new SysPage(ui->mainWidget);
    pageSystem->setFixedSize(1080,768);
    pageSystem->hide();
    connect(pageSystem->btnSysSave, SIGNAL(clicked(bool)), this, SLOT(saveConfig()));
    connect(pageSystem->cboBzbc, SIGNAL(currentIndexChanged(int)), this, SLOT(showBcdata()));

    addPageConfig();
    connect(pageConfig->btnRefresh, SIGNAL(clicked(bool)),this, SLOT(findAllSMV()));

    widgetInfo = new QWidget(this);
    //widgetInfo->setStyleSheet(".QWidget{background-color:rgb(204,102,0);border-radius:15px;}");
    //widgetInfo->setStyleSheet(".QWidget{background-color:#666;border-radius:15px;}");
    widgetInfo->setStyleSheet(".QWidget{background-color:qColor(250,250,0,150);border-radius:15px;}");

    labInfo = new QLabel("欢迎使用...");
    labInfo->setStyleSheet("color:yellow;font:22px;font-weight:bold;");
    labInfo->setFixedWidth(450);
    labInfo->setAlignment(Qt::AlignCenter);
    barTestProcess = new QProgressBar;
    barTestProcess->setMinimum(0);
    barTestProcess->setMaximum(100);
    barTestProcess->setTextVisible(false);
    barTestProcess->setValue(50);
    barTestProcess->hide();

    QVBoxLayout *layoutInfo = new QVBoxLayout;
    layoutInfo->setAlignment(Qt::AlignCenter);
    layoutInfo->addWidget(labInfo);
    layoutInfo->addWidget(barTestProcess);

    widgetInfo->setLayout(layoutInfo);
    widgetInfo->setFixedSize(450,110);
    widgetInfo->move(300,400);

    QTimer::singleShot(1000, widgetInfo, SLOT(hide()));

    autotestMask = new QWidget(this);
    autotestMask->setFixedSize(size());
    autotestMask->setStyleSheet(".QWidget{background-color:qColor(0,0,250,30);border-radius:15px;}");

    labAutoTestU = new QLabel("电流百分比 0%");
    labAutoTestU->setStyleSheet(".QLabel{color:blue; font-size:20px;}");
    labAutoTestI = new QLabel(" ,电流百分比 0%");
    labAutoTestI->setStyleSheet(".QLabel{color:blue; font-size:20px;}");
    labAutoTestCount = new QLabel();
    labAutoTestCount->setStyleSheet(".QLabel{color:yellow; font-size:20px;}");

    QHBoxLayout *layoutAutoIU = new QHBoxLayout;
    layoutAutoIU->addWidget(labAutoTestU);
    layoutAutoIU->addWidget(labAutoTestI);
    layoutAutoIU->addStretch(1);

    QHBoxLayout *layoutAutoCount = new QHBoxLayout;
    layoutAutoCount->addWidget(labAutoTestCount);
    layoutAutoCount->addStretch(1);

    labAutotestMask = new QLabel("自动测试进行中...");
    labAutotestMask->setStyleSheet(".QLabel{color:red; font-size:20px;}");

    btnAutotestMask = new QPushButton("停止测试");
    btnAutotestMask->setStyleSheet(".QPushButton{color:red; font-size:20px;min-width:200px;min-height:60px;}");
    connect(btnAutotestMask, SIGNAL(clicked(bool)), autotestMask, SLOT(hide()));
    connect(btnAutotestMask, SIGNAL(clicked(bool)), this, SLOT(stopAuto()));

    QHBoxLayout *layoutStatus = new QHBoxLayout;
    layoutStatus->addWidget(labAutotestMask);
    layoutStatus->addStretch(1);
    layoutStatus->addWidget(btnAutotestMask);

    QVBoxLayout *layoutAutotestMask = new QVBoxLayout;
    layoutAutotestMask->setContentsMargins(0,0,0,0);
    layoutAutotestMask->addStretch(1);
    layoutAutotestMask->addLayout(layoutAutoCount);
    layoutAutotestMask->addLayout(layoutAutoIU);
    layoutAutotestMask->addLayout(layoutStatus);

    autotestMask->setLayout(layoutAutotestMask);

    autotestMask->hide();
}

void MainWindow::addPageConfig()
{
    pageConfig = new configPage(ui->mainWidget);
    pageConfig->setGeometry(10, 360, 1070, 400);

    animation1 = new QPropertyAnimation(this);
    animation1->setStartValue( QPoint(1000, 360));
    animation1->setEndValue( QPoint(200, 360) );
    animation1->setDuration(200);
    animation1->setPropertyName("pos");
    animation1->setTargetObject(pageConfig);

    connect(ui->btnCfg, SIGNAL(clicked(bool)), this, SLOT(showPageConfig()));

    connect(pageConfig, SIGNAL(cfgDone()), this, SLOT(showPara()));

    showPara();
}

MainWindow::~MainWindow()
{
    packet_analyzer.kill();

    pageErrorTest->sourcePage->stopSrc();

    delete ui;
    delete myDB;
}

void MainWindow::showPageConfig()
{
    pageConfig->loadCfg();

    pageConfig->setGeometry(1000, 360, 1070, 400);
    pageConfig->show();

    animation1->start();
}

void MainWindow::on_btnClose_clicked()
{
    qApp->quit();
}

void MainWindow::btn_func_clicked()
{
    pageSystem->hide();
    pageResult->hide();
    stackedPages->show();

    int pageIndex = 0;

    QPushButton *funcBtn[6];
    funcBtn[0] = ui->btnFunc1_Error;
    funcBtn[1] = ui->btnFunc2_Smv;
    funcBtn[2] = ui->btnFunc3;
    funcBtn[3] = ui->btnFunc4;
    funcBtn[4] = ui->btnFunc5;
    funcBtn[5] = ui->btnFunc6;

    QPushButton *btnClicked = (QPushButton*)sender();

    if(!btnClicked->isChecked())
    {
        btnClicked->setChecked(true);
        return;
    }

    for(int i=0; i < 6; i++)
    {
        if( funcBtn[i] !=  btnClicked)
        {
            funcBtn[i]->setChecked(false);
        }
        else
        {
            pageIndex = i;
        }
    }

    qDebug()<<"changed to page:"<<pageIndex;
    stackedPages->setCurrentIndex(pageIndex);
}

void MainWindow::on_btnPhoto_clicked()
{
    QPixmap originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());

    QString format = "png";

    QDateTime time = QDateTime::currentDateTime();

    QString str = time.toString("yyyy-MM-dd-hh-mm-ss");

    QString filename = str + ".png";

    QDir toDir= QDir::currentPath();

    if(toDir.exists("c://model-2000/screenshot"))
    {
         qDebug() << "c://model-2000/screenshot/ is existed!";

         toDir.setPath("c://model-2000/screenshot");
         toDir.setFilter(QDir::Files);
         toDir.setSorting(QDir::Time);

         QFileInfoList list = toDir.entryInfoList();

         int i = 0;
         for(i=0 ; i<list.size(); i++)
         {
             if(i > 50)
             {
                 QFileInfo fileInfo = list.at(i);
                 toDir.remove( fileInfo.fileName() );

                 qDebug() << "Deleted file: "<<fileInfo.fileName();
             }
         }
    }
    else
    {
         qDebug() << "mkdir screenshot";
         toDir.mkdir("c://model-2000/screenshot");
         toDir.setPath("c://model-2000/screenshot");
    }

    filename = toDir.absolutePath()+ "/" + filename;

    if (!filename.isEmpty())
    {
         originalPixmap.save(filename, format.toAscii());
         QString s=tr("截图已保存！请及时使用 U 盘下载！");
        //         labInfo->setText(s);
        //         widgetInfo->show();
        //         showInfoTimer->start(2000);
    }
}

void MainWindow::on_btnResult_clicked()
{
    stackedPages->hide();

    pageSystem->hide();
    pageResult->show();

    dataCount=myDB->getWcxxCount();
    tbWcxx=myDB->openWcxx();

    if (tbWcxx.last())
        showWcdata();
    else
        pageResult->labDataCount->setText(tr("无数据"));
}

void MainWindow::on_btnSystem_clicked()
{
    stackedPages->hide();

    pageResult->hide();
    pageSystem->show();

    showBcdata();
}

void MainWindow::showPara()
{
    QString str="";

    QStringList sync;
    sync<<"同步输出"<<"电秒脉冲"<<"光秒脉冲"<<"B码电信号"<<"B码光信号"<<"1588 对时"<<"非同步";
    ui->labSync->setText(sync.at( pageConfig->sync_flag));

    if(pageConfig->voltageStdUnitIndex == 0)
    {
        str = " kV";
    }
    else
    {
        str = "/√3 kV";
    }

    ui->labPreV->setText(QString::number( pageConfig->voltagePre)+ str);
    ui->labPreI->setText(QString::number( pageConfig->currentPre)+" A");

    if(pageConfig->voltageStdIndex==0)
    {
        str = "100 V";
    }
    else if(pageConfig->voltageStdIndex==1)
    {
        str = "100/√3 V";
    }
    else
    {
        str = QString("小信号,%1V").arg(pageConfig->voltageSmall);
    }
    ui->labStdV->setText(str);

    if(pageConfig->currentStdIndex==0)
    {
        str = "1 A";
    }
    else if(pageConfig->currentStdIndex==1)
    {
        str = "5 A";
    }
    else
    {
        str = QString("小信号,%1V").arg(pageConfig->currentSmall);
    }

    ui->labStdI->setText(str);

    ui->labMU->setText(pageConfig->dutIndex==0?"IEC61850-9-2":"FT3");
    ui->labMAC->setText(pageConfig->macAddr);

    ui->labChUa->setText(QString::number( channelMapping[0]+1));
    ui->labChUb->setText(QString::number( channelMapping[1]+1));
    ui->labChUc->setText(QString::number( channelMapping[2]+1));
    ui->labChIa->setText(QString::number( channelMapping[3]+1));
    ui->labChIb->setText(QString::number( channelMapping[4]+1));
    ui->labChIc->setText(QString::number( channelMapping[5]+1));
}

void MainWindow::findAllSMV()
{
    smvList.clear();
    pageConfig->cboMacAddr->clear();

    if (cappacket->Open(0))
    {
        cappacket->setTestType(1);
        cappacket->StopCap(false);
        cappacket->setMacGl(1);
        cappacket->start();
    }
    else
    {
        qDebug()<<"初始化失败！";

        scanFinished();

        return;
    }

    QTimer::singleShot(1000, this, SLOT(scanFinished()));
}

void MainWindow::addList(QString app,QString mac,QString type,int cypl,int asdu)
{
    if (cypl < 4001)
    {
        cypl = 4000;
    }
    else
    {
        cypl = 12800;
    }

    int irowCount = smvList.size();

    if(irowCount > 0)
    {
        for(int i=0;i<irowCount;i++)
        {
            if( (smvList.at(i).app == app) && (smvList.at(i).mac == mac))
            {
                return;
            }
        }
    }

    qDebug()<<"new SMV"<<mac<<app;

    smvItem newSMV;

    newSMV.app = app;
    newSMV.mac = mac;
    newSMV.type = type;
    newSMV.cypl = cypl;
    newSMV.asdu = asdu;

    smvList.append(newSMV);
}

void MainWindow::scanFinished()
{
    qDebug()<<"scan finished!";

    cappacket->StopCap(true);

    if (cappacket->IsOpen())
        cappacket->Close();

    int irowCount = smvList.size();

    pageConfig->cboMacAddr->clear();

    if(irowCount > 0)
    {
        for(int i=0;i<irowCount;i++)
        {
            pageConfig->cboMacAddr->addItem(smvList.at(i).mac);
        }
    }
    else
    {
        pageConfig->cboMacAddr->addItem("None");
    }
}

void MainWindow::loadPortConfig()
{
    QSettings settings("HKEY_CURRENT_USER\\Software\\sanwei",QSettings::NativeFormat);

    etherPortName = settings.value("port").toString();

    qDebug() <<"etherPortName:"<< etherPortName;

    settings.deleteLater();
}

void MainWindow::initTestPara()
{
    pageErrorTest->btnStart->setText(tr("开始"));

    fakePPS->stop();

    cappacket->StopCap(true);

    if (cappacket->IsOpen())
        cappacket->Close();

    showControlFlag = -1;

    pageErrorTest->paintArea->update();

    udpCmd(0);

    if(pageErrorTest->sourcePage->sourceIsActive)
    {
        QEventLoop eventloop;
        QTimer::singleShot(500, &eventloop, SLOT(quit()));
        eventloop.exec();

        pageErrorTest->sourcePage->stopSrc();
    }
}

void MainWindow::startErrorTest()
{
    qDebug()<<"errorTest clicked!";

    if (pageErrorTest->btnStart->text()=="停止")
    {
        initTestPara();

        return;
    }

    pageErrorTest->btnStart->setText(tr("停止"));

    newStart = true;

    pageErrorTest->mainPages->setCurrentIndex(0);

    if(pageConfig->voltageStdIndex == 0)
    {
        //UTestXs = 1 ; //100V
        udp->maxValueStd[0]=udp->maxValueStd[1]=udp->maxValueStd[2] = 100;
    }
    else
    {
        //UTestXs = 100 / 57.73505;//100√3V
        udp->maxValueStd[0]=udp->maxValueStd[1]=udp->maxValueStd[2] = 57.73505;
    }

    if(pageConfig->currentStdIndex == 0)
    {
        udp->maxValueStd[3]=udp->maxValueStd[4]=udp->maxValueStd[5] = 1;
        //ITestXs = 100; //5A
    }
    else
    {
        udp->maxValueStd[3]=udp->maxValueStd[4]=udp->maxValueStd[5] = 5;
        //ITestXs = 20; //1A
    }

    qDebug()<<"udp->maxValueStd[0]"<<udp->maxValueStd[0];
    qDebug()<<"udp->maxValueStd[3]"<<udp->maxValueStd[3];

    voltagePre = pageConfig->voltagePre * 1000;
    if(pageConfig->voltageStdUnitIndex == 1)
    {
        voltagePre  = voltagePre * 0.5773505;
    }
    currentPre=pageConfig->currentPre;

    cappacket->maxValueMu[0]=cappacket->maxValueMu[1]=cappacket->maxValueMu[2]=voltagePre;
    cappacket->maxValueMu[3]=cappacket->maxValueMu[4]=cappacket->maxValueMu[5]=pageConfig->currentPre;

    read_wcbc_from_db();

    saveMuinfo();

    if(pageConfig->sync_flag != 6)
    {
        cappacket->setUnSync(false);
    }
    else
    {
        cappacket->setUnSync(true);
        cappacket->muDelayGived = pageConfig->inputDelay->text().toDouble();
    }

    pageErrorTest->sourcePage->startSrc();

    source_has_been_reconfiged = 0;

    fakePPS->start(200);

    int testType = 'A';

    if(pageConfig->dutIndex == 0) // mu output is 9-2
    {
        NetTest_mu();

        testType = 'A';
    }
    else if(pageConfig->dutIndex == 1)            //Ft3
    {
        udp->setFt3Enable(true);

        for(int i = 0; i < 6; i++)
        {
            udp->setFt3Channel(i, channelMapping[i]);
        }

        udp->ft3_factor_voltage = 100 / 11585.0;

        if(pageConfig->btnInstrument->isChecked())
        {
            udp->ft3_factor_current = 100 / 11585.0;
        }
        else
        {
            udp->ft3_factor_current = 100 / 463.0;
        }

        testType = 'C';
    }

    udpCmd(testType);

    newSaveCycle = true;
}

void MainWindow::read_wcbc_from_db()
{
    QStringList wcbc_key;
    wcbc_key<<"00"<<"11"<<"04"<<"14"<<"24"<<"44";// Ua, Ub, Uc, Ia, Ib, Ic

    for (int i = 0; i < wcbc_key.size(); ++i)
    {
        QSqlQuery tbWcbc=myDB->openWcxxforSql("select * from wcbc where type='"+ wcbc_key.at(i) +"'");

        if (tbWcbc.next())
        {
            wcbc_array[i][0] = tbWcbc.value(7).toFloat();
            wcbc_array[i][1] = tbWcbc.value(8).toFloat();
            wcbc_array[i][2] = tbWcbc.value(1).toFloat();
            wcbc_array[i][3] = tbWcbc.value(2).toFloat();
            wcbc_array[i][4] = tbWcbc.value(3).toFloat();
            wcbc_array[i][5] = tbWcbc.value(4).toFloat();
            wcbc_array[i][6] = tbWcbc.value(5).toFloat();
            wcbc_array[i][7] = tbWcbc.value(6).toFloat();
        }
        else
        {
            wcbc_array[i][0] = 0;
            wcbc_array[i][1] = 0;
            wcbc_array[i][2] = 0;
            wcbc_array[i][3] = 0;
            wcbc_array[i][4] = 0;
            wcbc_array[i][5] = 0;
            wcbc_array[i][6] = 0;
            wcbc_array[i][7] = 0;
        }

        tbWcbc.clear();
    }

    myDB->getXTCS();
    tbsx=myDB->m_Tbsx;
}

void MainWindow::NetTest_mu()
{
    int iTestMode = 'A';

    static int try_to_open = 2;

    if (!cappacket->IsOpen())
    {
        if(try_to_open--)
        {
            cappacket->Open(1);

            QTimer::singleShot(500, this, SLOT(NetTest_mu()));

            qDebug()<<"Try to open the port,"<<try_to_open;

            return;
        }
        else
        {
            try_to_open = 2;

            showInfo("读取9-2报文失败，请检查网络连接后重试！");

            initTestPara();
        }
    }
    else
    {
        qDebug()<<"the port is open!";

        try_to_open = 2;

        cappacket->setTestType(iTestMode);

        setCSCS(iTestMode);

         showControlFlag = 'A';

        for(int i = 0; i < 6; i++)
        {
            cappacket->setChannelMU(i, channelMapping[i]);
        }

        cappacket->readyToSample(); // begin to sample when the next iSmpCnt == 0

        cappacket->StopCap(false);

        cappacket->start();

        qDebug()<< "NetTest_mu(), start...";
    }
}

void MainWindow::jsMutWc()
{
    if(pps_count < 5) // if no udp is received, do cal every 200*5 ms
    {
        pps_count++;
    }
    else
    {
        pps_count = 0;
    }

    if(pps_count != 3) return;


    qDebug()<<"all data is ready...show the result!";

    processMuData();    // compute and show the data

    udp->setIsOK(false);
}

void MainWindow::processMuData()
{
    bool isFt3 = false;

    if(pageConfig->dutIndex == 1)
    {
        isFt3 = true;
    }
    else
    {
        if(cappacket->getSync())
        {
            pageErrorTest->labSync->setText("已同步");
            pageErrorTest->labSync->setStyleSheet("color:green;font-size:15px;font-weight:bold;border:1px solid gray;");
        }
        else
        {
            pageErrorTest->labSync->setText("未同步");
            pageErrorTest->labSync->setStyleSheet("color:red;font-size:15px;font-weight:bold;border:1px solid gray;");
        }
    }

    static double mu_yxz_buf[6] = {0};
    static double mu_xw_buf[6] = {0};

    static double std_yxz_buf[6] = {0};
    static double std_xw_buf[6] = {0};

//    double voltage_real[3];
//    double current_real[3];

    double *mu_yxz, *mu_xw;
    double *std_yxz, *std_xw;

//    qDebug()<<"cboDataTime->currentIndex()"<<tbsx;
//    qDebug()<<"cboBcSelect->currentText()"<<newTestPage->cboBcSelect->currentText();

    if(tbsx == 1)
    {
        mu_yxz = mu_yxz_buf;
        mu_xw = mu_xw_buf;

        std_yxz = udp->dblYxzUdp;
        std_xw = udp->dblXwUdp;
    }
    else if(tbsx == 2)
    {
        if(isFt3)
        {
            mu_yxz = udp->dblYxzUdp_ft3;
            mu_xw = udp->dblXwUdp_ft3;
        }
        else
        {
            mu_yxz = cappacket->mu_dblYxz;
            mu_xw = cappacket->mu_dblXw;
        }

        std_yxz = std_yxz_buf;
        std_xw = std_xw_buf;
    }
    else
    {
        if(isFt3)
        {
            mu_yxz = udp->dblYxzUdp_ft3;
            mu_xw = udp->dblXwUdp_ft3;
        }
        else
        {
            mu_yxz = cappacket->mu_dblYxz;
            mu_xw = cappacket->mu_dblXw;
        }

        std_yxz = udp->dblYxzUdp;
        std_xw = udp->dblXwUdp;
    }

    for(int ind = 0; ind < 6; ind++)
    {
        std_yxz[ind] += wcbc_array[ind][0];
        std_xw[ind] += wcbc_array[ind][1];

        if (std_yxz[ind] < 2.0)
        {
            std_yxz[ind] += wcbc_array[ind][2];
            std_xw[ind] += wcbc_array[ind][3];
        }
        else if (std_yxz[ind] < 10.0)
        {
            std_yxz[ind] += wcbc_array[ind][4];
            std_xw[ind] += wcbc_array[ind][5];
        }
        else
        {
            std_yxz[ind] += wcbc_array[ind][6];
            std_xw[ind] += wcbc_array[ind][7];
        }
    }

    // phase compensate for unSync mode
    double muPhaseCompensate = 0;
    if(pageConfig->sync_flag == 6)
    {
        double time2percent = 36*6*(udp->getPL())/10000;

        if(pageConfig->dutIndex == 0)
        {
            if (cappacket->muDelayRead != 0) //if gived, don't read
            {
                muPhaseCompensate = (cappacket->muDelayRead - cappacket->time_stamp_mini)* time2percent;

                pageConfig->inputDelay->setText(QString::number( cappacket->muDelayRead));
            }
            else
            {
                muPhaseCompensate = (cappacket->muDelayGived - cappacket->time_stamp_mini) * time2percent;
            }
        }
        else
        {
            double delay_default =  pageConfig->inputDelay->text().toFloat();

            if(delay_default == 0)
            {
                delay_default = udp->delay_in_packet;

                pageConfig->inputDelay->setText(QString::number(delay_default));
            }

            muPhaseCompensate = delay_default * time2percent;
        }

        qDebug() <<"muPhaseCompensate"<<muPhaseCompensate<<time2percent;
    }

    pageErrorTest->labAUPhaseReal->setText(QString::number(std_xw[0],'f',2));
    pageErrorTest->labBUPhaseReal->setText(QString::number(std_xw[1],'f',2));
    pageErrorTest->labCUPhaseReal->setText(QString::number(std_xw[2],'f',2));

    pageErrorTest->labAIPhaseReal->setText(QString::number(std_xw[3],'f',2));
    pageErrorTest->labBIPhaseReal->setText(QString::number(std_xw[4],'f',2));
    pageErrorTest->labCIPhaseReal->setText(QString::number(std_xw[5],'f',2));

    pageErrorTest->labPhaseAUTest->setText(infnan(QString::number(mu_yxz[0],'f',5)));
    pageErrorTest->labPhaseBUTest->setText(infnan(QString::number(mu_yxz[1],'f',5)));
    pageErrorTest->labPhaseCUTest->setText(infnan(QString::number(mu_yxz[2],'f',5)));

    pageErrorTest->labPhaseAITest->setText(infnan(QString::number(mu_yxz[3],'f',5)));
    pageErrorTest->labPhaseBITest->setText(infnan(QString::number(mu_yxz[4],'f',5)));
    pageErrorTest->labPhaseCITest->setText(infnan(QString::number(mu_yxz[5],'f',5)));

    pageErrorTest->labAUPhaseTest->setText(QString::number(mu_xw[0],'f',2));
    pageErrorTest->labBUPhaseTest->setText(QString::number(mu_xw[1],'f',2));
    pageErrorTest->labCUPhaseTest->setText(QString::number(mu_xw[2],'f',2));

    pageErrorTest->labAIPhaseTest->setText(QString::number(mu_xw[3],'f',2));
    pageErrorTest->labBIPhaseTest->setText(QString::number(mu_xw[4],'f',2));
    pageErrorTest->labCIPhaseTest->setText(QString::number(mu_xw[5],'f',2));

    for(int ind = 0; ind< 6; ind++)
    {
        if ( ( phaseError[ind] = mu_xw[ind] - std_xw[ind] + muPhaseCompensate) > 20000)
            phaseError[ind]-=21600;

        if( std_yxz[ind] != 0)
        {
            ratioError[ind] = (mu_yxz[ind] - std_yxz[ind])*100/ std_yxz[ind];
        }
        else
        {
            ratioError[ind] = 0;
        }

        //qDebug()<<"result:"<<ratioError[ind]<<phaseError[ind];
    }

    resultFilter();//滤波

    pageErrorTest->labPhaseAUDelay->setText(QString::number(phaseError[0],'f',2));
    pageErrorTest->labPhaseBUDelay->setText(QString::number(phaseError[1],'f',2));
    pageErrorTest->labPhaseCUDelay->setText(QString::number(phaseError[2],'f',2));
    pageErrorTest->labPhaseAIDelay->setText(QString::number(phaseError[3],'f',2));
    pageErrorTest->labPhaseBIDelay->setText(QString::number(phaseError[4],'f',2));
    pageErrorTest->labPhaseCIDelay->setText(QString::number(phaseError[5],'f',2));

    pageErrorTest->labPhaseAUReal->setText(infnan(QString::number(std_yxz[0],'f',5)));
    pageErrorTest->labPhaseBUReal->setText(infnan(QString::number(std_yxz[1],'f',5)));
    pageErrorTest->labPhaseCUReal->setText(infnan(QString::number(std_yxz[2],'f',5)));

    pageErrorTest->labPhaseAIReal->setText(infnan(QString::number(std_yxz[3],'f',5)));
    pageErrorTest->labPhaseBIReal->setText(infnan(QString::number(std_yxz[4],'f',5)));
    pageErrorTest->labPhaseCIReal->setText(infnan(QString::number(std_yxz[5],'f',5)));

    pageErrorTest->labPhaseAUError->setText(infnan(QString::number(ratioError[0],'f',4)));
    pageErrorTest->labPhaseBUError->setText(infnan(QString::number(ratioError[1],'f',4)));
    pageErrorTest->labPhaseCUError->setText(infnan(QString::number(ratioError[2],'f',4)));
    pageErrorTest->labPhaseAIError->setText(infnan(QString::number(ratioError[3],'f',4)));
    pageErrorTest->labPhaseBIError->setText(infnan(QString::number(ratioError[4],'f',4)));
    pageErrorTest->labPhaseCIError->setText(infnan(QString::number(ratioError[5],'f',4)));

    memcpy(std_yxz_buf, udp->dblYxzUdp, sizeof(std_yxz_buf));
    memcpy(std_xw_buf, udp->dblXwUdp,sizeof(std_xw_buf));

    if(isFt3)
    {
        memcpy(mu_yxz_buf, udp->dblYxzUdp_ft3, sizeof(mu_yxz_buf));
        memcpy(mu_xw_buf, udp->dblXwUdp_ft3, sizeof(mu_xw_buf));

        ///newTestPage->widget-> update();
    }
    else
    {
        memcpy(mu_yxz_buf, cappacket->mu_dblYxz, sizeof(mu_yxz_buf));
        memcpy(mu_xw_buf, cappacket->mu_dblXw, sizeof(mu_xw_buf));
    }

    if(pageErrorTest->extPages->currentIndex() == 0)
    {
        pageErrorTest->paintArea->update();
    }
    else if(pageErrorTest->extPages->currentIndex() == 2)
    {
        analyzeHarmonic();

        paintHarmonic();

        return;
    }
    else if(pageErrorTest->extPages->currentIndex() == 1)
    {
        errorStatistics();
    }
    else
    {
#if 0
        pageErrorTest->powerAnalyze->labRMS[0]->setText(showDbl( mu_yxz[0] * voltagePre));
        pageErrorTest->powerAnalyze->labRMS[1]->setText(showDbl( mu_yxz[1] * voltagePre));
        pageErrorTest->powerAnalyze->labRMS[2]->setText(showDbl( mu_yxz[2] * voltagePre));

        pageErrorTest->powerAnalyze->labRMS[3]->setText(showDbl(mu_yxz[3] * currentPre));
        pageErrorTest->powerAnalyze->labRMS[4]->setText(showDbl(mu_yxz[4] * currentPre));
        pageErrorTest->powerAnalyze->labRMS[5]->setText(showDbl(mu_yxz[5] * currentPre));

        double tmp[3];
        tmp[0] = cos( PI*(mu_xw[3] - mu_xw[0])/10800);
        pageErrorTest->powerAnalyze->labPowerFactorA->setText(showDbl(tmp[0]));
        tmp[1] = cos( PI*(mu_xw[4] - mu_xw[1])/10800);
        pageErrorTest->powerAnalyze->labPowerFactorB->setText(showDbl(tmp[1]));
        tmp[2] = cos( PI*(mu_xw[5] - mu_xw[2])/10800);
        pageErrorTest->powerAnalyze->labPowerFactorC->setText(showDbl(tmp[2]));

        tmp[0] = tmp[0] * mu_yxz[0] * mu_yxz[3] * voltagePre * currentPre;
        pageErrorTest->powerAnalyze->labPowerA->setText(showDbl(tmp[0]));
        tmp[1] = tmp[1] * mu_yxz[1] * mu_yxz[4] * voltagePre * currentPre;
        pageErrorTest->powerAnalyze->labPowerB->setText(showDbl(tmp[1]));
        tmp[2] = tmp[2] * mu_yxz[2] * mu_yxz[5] * voltagePre * currentPre;
        pageErrorTest->powerAnalyze->labPowerC->setText(showDbl(tmp[2]));

        pageErrorTest->powerAnalyze->labPowerReactiveA->setText(showDbl(tmp[2]));
        pageErrorTest->powerAnalyze->labPowerReactiveB->setText(showDbl(tmp[2]));
        pageErrorTest->powerAnalyze->labPowerReactiveC->setText(showDbl(tmp[2]));

        pageErrorTest->powerAnalyze->paintArea->phase[0] = mu_xw[0] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[1] = mu_xw[1] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[2] = mu_xw[2] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[3] = mu_xw[3] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[4] = mu_xw[4] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[5] = mu_xw[5] /60;

        pageErrorTest->powerAnalyze->paintArea->update();
#else
        pageErrorTest->powerAnalyze->labRMS[0]->setText(showDbl( std_yxz[0] * voltagePre/100000.0));
        pageErrorTest->powerAnalyze->labRMS[1]->setText(showDbl( std_yxz[1] * voltagePre/100000.0));
        pageErrorTest->powerAnalyze->labRMS[2]->setText(showDbl( std_yxz[2] * voltagePre/100000.0));

        pageErrorTest->powerAnalyze->labRMS[3]->setText(showDbl( std_yxz[3] * currentPre/100.0));
        pageErrorTest->powerAnalyze->labRMS[4]->setText(showDbl( std_yxz[4] * currentPre/100.0));
        pageErrorTest->powerAnalyze->labRMS[5]->setText(showDbl( std_yxz[5] * currentPre/100.0));

        double tmp[3];
        tmp[0] = cos( PI*(std_xw[3] - std_xw[0])/10800);
        pageErrorTest->powerAnalyze->labPowerFactorA->setText(showDbl(tmp[0]));
        tmp[1] = cos( PI*(std_xw[4] - std_xw[1])/10800);
        pageErrorTest->powerAnalyze->labPowerFactorB->setText(showDbl(tmp[1]));
        tmp[2] = cos( PI*(std_xw[5] - std_xw[2])/10800);
        pageErrorTest->powerAnalyze->labPowerFactorC->setText(showDbl(tmp[2]));

        double tm_pwr = tmp[0] * std_yxz[0] * std_yxz[3] * voltagePre * currentPre/10000000.0;
        pageErrorTest->powerAnalyze->labPowerA->setText(showDbl(tm_pwr));
        tm_pwr = tmp[1] * std_yxz[1] * std_yxz[4] * voltagePre * currentPre/10000000.0;
        pageErrorTest->powerAnalyze->labPowerB->setText(showDbl(tm_pwr));
        tm_pwr = tmp[2] * std_yxz[2] * std_yxz[5] * voltagePre * currentPre/10000000.0;
        pageErrorTest->powerAnalyze->labPowerC->setText(showDbl(tm_pwr));

        tmp[0] = sqrt(1-tmp[0]*tmp[0]); // cos() to sin()
        tmp[1] = sqrt(1-tmp[1]*tmp[1]);
        tmp[2] = sqrt(1-tmp[2]*tmp[2]);

        tm_pwr = tmp[0] * std_yxz[0] * std_yxz[3] * voltagePre * currentPre/10000000.0;
        pageErrorTest->powerAnalyze->labPowerReactiveA->setText(showDbl(tm_pwr));
        tm_pwr = tmp[1] * std_yxz[1] * std_yxz[4] * voltagePre * currentPre/10000000.0;
        pageErrorTest->powerAnalyze->labPowerReactiveB->setText(showDbl(tm_pwr));
        tm_pwr = tmp[2] * std_yxz[2] * std_yxz[5] * voltagePre * currentPre/10000000.0;
        pageErrorTest->powerAnalyze->labPowerReactiveC->setText(showDbl(tm_pwr));

        pageErrorTest->powerAnalyze->paintArea->phase[0] = std_xw[0] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[1] = std_xw[1] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[2] = std_xw[2] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[3] = std_xw[3] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[4] = std_xw[4] /60;
        pageErrorTest->powerAnalyze->paintArea->phase[5] = std_xw[5] /60;

        pageErrorTest->powerAnalyze->paintArea->update();
#endif
    }

    if (pageAuto->btnTest->text() == "停止测量")
    {
        if ((jingdu_count > 15) && (jingdu_count < 76))
        {
            UaErr += pageErrorTest->labPhaseAUError->text().toDouble() / 60.0;
            UbErr += pageErrorTest->labPhaseBUError->text().toDouble() / 60.0;
            UcErr += pageErrorTest->labPhaseCUError->text().toDouble() / 60.0;
            IaErr += pageErrorTest->labPhaseAIError->text().toDouble() / 60.0;
            IbErr += pageErrorTest->labPhaseBIError->text().toDouble() / 60.0;
            IcErr += pageErrorTest->labPhaseCIError->text().toDouble() / 60.0;

            UaErr_p += pageErrorTest->labPhaseAUDelay->text().toDouble() / 60.0;
            UbErr_p += pageErrorTest->labPhaseBUDelay->text().toDouble() / 60.0;
            UcErr_p += pageErrorTest->labPhaseCUDelay->text().toDouble() / 60.0;
            IaErr_p += pageErrorTest->labPhaseAIDelay->text().toDouble() / 60.0;
            IbErr_p += pageErrorTest->labPhaseBIDelay->text().toDouble() / 60.0;
            IcErr_p += pageErrorTest->labPhaseCIDelay->text().toDouble() / 60.0;

            labAutoTestCount->setText(QString("第 %1 次，共 60 次").arg(jingdu_count-15));
        }

        jingdu_count++; //测试进度
    }

//    if(m_bIsConn)
//    {
//        QString s = "1a:";

//        s += newTestPage->labPhaseAUReal->text();
//        s += ":" + newTestPage->labPhaseBUReal->text();
//        s += ":" + newTestPage->labPhaseCUReal->text();
//        s += ":" + newTestPage->labPhaseAIReal->text();
//        s += ":" + newTestPage->labPhaseBIReal->text();
//        s += ":" + newTestPage->labPhaseCIReal->text();

//        s += ":" + newTestPage->labPhaseAUTest->text();
//        s += ":" + newTestPage->labPhaseBUTest->text();
//        s += ":" + newTestPage->labPhaseCUTest->text();
//        s += ":" + newTestPage->labPhaseAITest->text();
//        s += ":" + newTestPage->labPhaseBITest->text();
//        s += ":" + newTestPage->labPhaseCITest->text();

//        s += ":" + newTestPage->labPhaseAUError->text();
//        s += ":" + newTestPage->labPhaseBUError->text();
//        s += ":" + newTestPage->labPhaseCUError->text();
//        s += ":" + newTestPage->labPhaseAIError->text();
//        s += ":" + newTestPage->labPhaseBIError->text();
//        s += ":" + newTestPage->labPhaseCIError->text();

//        s += ":" + newTestPage->labAUPhaseReal->text();
//        s += ":" + newTestPage->labBUPhaseReal->text();
//        s += ":" + newTestPage->labCUPhaseReal->text();
//        s += ":" + newTestPage->labAIPhaseReal->text();
//        s += ":" + newTestPage->labBIPhaseReal->text();
//        s += ":" + newTestPage->labCIPhaseReal->text();

//        s += ":" + newTestPage->labAUPhaseTest->text();
//        s += ":" + newTestPage->labBUPhaseTest->text();
//        s += ":" + newTestPage->labCUPhaseTest->text();
//        s += ":" + newTestPage->labAIPhaseTest->text();
//        s += ":" + newTestPage->labBIPhaseTest->text();
//        s += ":" + newTestPage->labCIPhaseTest->text();

//        s += ":" + newTestPage->labPhaseAUDelay->text();
//        s += ":" + newTestPage->labPhaseBUDelay->text();
//        s += ":" + newTestPage->labPhaseCUDelay->text();
//        s += ":" + newTestPage->labPhaseAIDelay->text();
//        s += ":" + newTestPage->labPhaseBIDelay->text();
//        s += ":" + newTestPage->labPhaseCIDelay->text();

//        tcpServer->TcpSend(s);

//        int showIndex = 0;
//        for (;showIndex < 6; showIndex++)
//        {
//            if( newTestPage->digi_tdlb_show[showIndex] ) break;
//        }

//        QString strBuff="1b";
//        double (*udpSamplesArray)[10*80];

//        udpSamplesArray = &((*udp->showArray)[showIndex]);

//        int NumOfSamples = 80;

//        for(int i = 0; i < NumOfSamples; i++)
//        {
//            strBuff += ":" + QString::number((*udpSamplesArray)[i],'f',4);
//        }

//        tcpServer->TcpSend(strBuff);

//        strBuff.clear();
//        strBuff="1c";
//        double (*muSamplesArray)[10*256];

//        if(isFt3)
//        {
//            NumOfSamples = udp->ft3SamplesPerCycle();
//            muSamplesArray = &((*udp->showArray_ft3)[showIndex]);
//        }
//        else
//        {
//            NumOfSamples = cappacket->SmpRate();
//            muSamplesArray = &((*cappacket->mu_showArray)[showIndex]);
//        }

//        for(int i = 0; i < NumOfSamples; i++)
//        {
//            strBuff += ":" + QString::number((*muSamplesArray)[i],'f',4);
//        }

//        tcpServer->TcpSend(strBuff);
//    }
//    qDebug()<<"ProcessMuData(), do nothing so far...";
}

void MainWindow::errorStatistics()
{
    if(error_statistics_count == 0)
    {
        memset(ratioError_avg, 0x00, sizeof(ratioError_avg));
        memset(phaseError_avg, 0x00, sizeof(phaseError_avg));

        memset(ratioError_rms, 0x00, sizeof(ratioError_rms));
        memset(phaseError_rms, 0x00, sizeof(phaseError_rms));

        memset(ratioError_max, 0x00, sizeof(ratioError_max));
        memset(phaseError_max, 0x00, sizeof(phaseError_max));
    }

    int times = pageErrorTest->resultAnalyze->inputStatisticalTimes->text().toInt();

    if(times == 0) times = 5;

    double tmp_r = 0;
    double tmp_p = 0;

    if(error_statistics_count < times)
    {
        for(int ind = 0; ind< 6; ind++)
        {
            ratioError_avg[ind] += ratioError[ind]; // sum
            phaseError_avg[ind] += phaseError[ind];

            ratioError_rms[ind] += ratioError[ind]*ratioError[ind]; // sum of square
            phaseError_rms[ind] += phaseError[ind]*phaseError[ind];

            tmp_r = fabs(ratioError[ind]);
            tmp_p = fabs(phaseError[ind]);

            if(tmp_r > ratioError_max[ind])
            {
                ratioError_max[ind] = tmp_r;
            }

            if(tmp_p > phaseError_max[ind])
            {
                phaseError_max[ind] = tmp_p;
            }
        }

        error_statistics_count++;
    }
    else
    {
        for(int ind = 0; ind< 6; ind++)
        {
            ratioError_avg[ind] /= times;
            phaseError_avg[ind] /= times; // average

            //ratioError_rms[ind] /= times;
            //phaseError_rms[ind] /= times;

            ratioError_rms[ind] = sqrt(ratioError_rms[ind]/times);
            phaseError_rms[ind] = sqrt(phaseError_rms[ind]/times); // root mean square

            pageErrorTest->resultAnalyze->r_avg[ind]->setText(showDbl(ratioError_avg[ind]));
            pageErrorTest->resultAnalyze->p_avg[ind]->setText(showDbl(phaseError_avg[ind]));

            pageErrorTest->resultAnalyze->r_rms[ind]->setText(showDbl(ratioError_rms[ind]));
            pageErrorTest->resultAnalyze->p_rms[ind]->setText(showDbl(phaseError_rms[ind]));

            pageErrorTest->resultAnalyze->r_max[ind]->setText(showDbl(ratioError_max[ind]));
            pageErrorTest->resultAnalyze->p_max[ind]->setText(showDbl(phaseError_max[ind]));
        }

        error_statistics_count = 0;
    }
}

void MainWindow::resultFilter()
{
    static int iAvg = 0;

    static double Ua_bc[5];
    static double Ua_jc[5];

    static double Ia_bc[5];
    static double Ia_jc[5];

    static double Ub_bc[5];
    static double Ub_jc[5];

    static double Ib_bc[5];
    static double Ib_jc[5];

    static double Uc_bc[5];
    static double Uc_jc[5];

    static double Ic_bc[5];
    static double Ic_jc[5];

    qDebug()<<"result filter:"<<ratioError[3]<<ratioError[4]<<ratioError[5];

    if(!newStart)
    {
        Ua_bc[iAvg] = ratioError[0];
        Ub_bc[iAvg] = ratioError[1];
        Uc_bc[iAvg] = ratioError[2];

        Ia_bc[iAvg] = ratioError[3];
        Ib_bc[iAvg] = ratioError[4];
        Ic_bc[iAvg] = ratioError[5];

        Ua_jc[iAvg] = phaseError[0];
        Ub_jc[iAvg] = phaseError[1];
        Uc_jc[iAvg] = phaseError[2];

        Ia_jc[iAvg] = phaseError[3];
        Ib_jc[iAvg] = phaseError[4];
        Ic_jc[iAvg] = phaseError[5];

        if ( iAvg == 4)
        {
            iAvg = 0;
        }
        else
        {
            iAvg++;
        }
    }
    else
    {
        for(int i = 0; i < 5; i++)
        {
            Ua_bc[i] = ratioError[0];
            Ub_bc[i] = ratioError[1];
            Uc_bc[i] = ratioError[2];

            Ia_bc[i] = ratioError[3];
            Ib_bc[i] = ratioError[4];
            Ic_bc[i] = ratioError[5];

            Ua_jc[i] = phaseError[0];
            Ub_jc[i] = phaseError[1];
            Uc_jc[i] = phaseError[2];

            Ia_jc[i] = phaseError[3];
            Ib_jc[i] = phaseError[4];
            Ic_jc[i] = phaseError[5];
        }

        iAvg = 0;
        newStart = false;
    }

    ratioError[0] = SZLB(5, Ua_bc);
    ratioError[1] = SZLB(5, Ub_bc);
    ratioError[2] = SZLB(5, Uc_bc);
    ratioError[3] = SZLB(5, Ia_bc);
    ratioError[4] = SZLB(5, Ib_bc);
    ratioError[5] = SZLB(5, Ic_bc);

    phaseError[0] = SZLB(5, Ua_jc);
    phaseError[1] = SZLB(5, Ub_jc);
    phaseError[2] = SZLB(5, Uc_jc);
    phaseError[3] = SZLB(5, Ia_jc);
    phaseError[4] = SZLB(5, Ib_jc);
    phaseError[5] = SZLB(5, Ic_jc);

    qDebug()<<"result filter:"<<ratioError[3]<<ratioError[4]<<ratioError[5];
}

double MainWindow::SZLB(int num,double*D_ADD)//num组double类型的数，去掉一个最大一个最小，再取平均
{
    int i;
    double Max_Data;
    double Min_Data;
    double Result;

    Max_Data=Min_Data=Result=*D_ADD;

    for(i=1;i<num;i++)
    {
        Result+=(*(D_ADD+i));

        if(*(D_ADD+i)<Min_Data)
        {
            Min_Data=*(D_ADD+i);
        }
        if(*(D_ADD+i)>Max_Data)
        {
            Max_Data=*(D_ADD+i);
        }
    }
    if(num<=2)
        Result=(Result/num);	//如果num<=3,则num个数直接取平均
    else
        Result=(Result-Max_Data-Min_Data)/(num-2);//num>3,num个数去掉一个最大一个最小，再取平均
    return(Result);
}

QString MainWindow::infnan(QString s)
{
    if(s.length() > 8) return s.left(8);

    if ((s=="inf")||(s=="nan"))
        return "/";
    else
        return s;
}

QString MainWindow::showDbl(double dbl)
{
    QString str = QString::number(dbl, 'f', 6);

    return infnan(str);
}

void MainWindow::setCSCS(int iTestMode)
{
    if (iTestMode==3)    //全帧解析
    {
        cappacket->SetCapParamater(TestChannel_LuBo,1,0,1);//通道，周期,起始位,幅值
    }
    else if(iTestMode == 'A')
    {
        cappacket->SetCapParamater(1,1,0,1);
    }
    else
    {
        cappacket->SetCapParamater(1,1,0,1);//通道，周期,起始位,幅值
    }

    cappacket->setTestChannel(1);
}

void MainWindow::saveMuinfo()
{
    QString sql="update muinfo set appid='";
    sql += "0000',mac='";
    sql += pageConfig->macAddr +"',cypl='4000',asdu='12'";

    myDB->openWcxxforSql(sql);
}

void MainWindow::triggerPPS()
{
    pps_count = 0;

    if(source_has_been_reconfiged++ <2) //don't send the first three to serial port
    {
        return;
    }

    source_has_been_reconfiged = 3;

    union the_data{
        char byte[4];
        float value;
    } data;

    QByteArray cmd_feed_bak = "#";

    cmd_feed_bak[1] = 48;

    for(int i=0; i<6; i++)
    {
       data.value = udp->dblYxzUdp[i] * udp->maxValueStd[i];
       cmd_feed_bak += QByteArray::fromRawData(data.byte, 4);

       //qDebug()<<"cmd_feed_back:"<<cmd_feed_bak.toHex();

       data.value = udp->dblXwUdp[i];
       cmd_feed_bak += QByteArray::fromRawData(data.byte, 4);

       //qDebug()<<"cmd_feed_back:"<<cmd_feed_bak.toHex();
    }

    pageErrorTest->sourcePage->feedback(cmd_feed_bak);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (showControlFlag == -1)
    {
        if(obj == pageErrorTest->paintArea)
        {
            if (event->type() == QEvent::Paint)
            {
                paintBlank(pageErrorTest->paintArea);
                return true;
            }
        }
    }
    else if (showControlFlag == 'A') // mu tester
    {
        if (obj == pageErrorTest->paintArea)
        {
            if (event->type() == QEvent::Paint)
            {
                paintForMu(pageErrorTest->paintArea);
                return true;
            }
        }
    }
    else if (showControlFlag == 3)
    {
        for(int i=0;i<12;i++)
        {
            if (obj == pageErrorTest->pageAll->subPages[i])
            {
                if (event->type() == QEvent::Paint)
                {
                    for(int j=0;j<12;j++)
                    {
                        if (j!=i)
                            cappacket->SetChannelShow(j,false);
                    }

                    paintOnAll(pageErrorTest->pageAll->subPages[i]);

                    qDebug()<<"paint all";

                    for(int i=0;i<12;i++)
                        cappacket->SetChannelShow(i,true);

                    return QWidget::eventFilter(obj, event);
                }
            }
        }
    }
    else if (showControlFlag == 'S')
    {
        if(obj == pageBwjy->paintArea)
        {
            if (event->type() == QEvent::Paint)
            {
                paintonSZB(pageBwjy->paintArea);

                return true;
            }
        }
    }
    else if (showControlFlag == 'L')
    {
        if(obj == pageLubo->paintArea)
        {
            if (event->type() == QEvent::Paint)
            {
                paintOnLubo(pageLubo->paintArea);

                return true;
            }
        }
    }

    return QWidget::eventFilter(obj, event);
}

void MainWindow::paintBlank(QWidget *w)
{
    QPainter painter(w);
    painter.translate(0,100);
    painter.drawLine(0,0,800,0);
}

void MainWindow::paintForMu(QWidget *w)
{
    qDebug()<< "paint begin...";

    bool isFt3 = false;

    if(pageConfig->dutIndex == 1)
    {
        isFt3 = true;
    }

    QPainter painter(w);
    QPoint beginPoint;
    QPoint endPoint;
    painter.translate(0,100);
    painter.drawLine(0,0,800,0);

    double (*showArray)[10*256];
    double (*showArray_udp)[10*80];

    float dblWidth, dblHeight;
    dblWidth = (float)w->width();
    dblHeight = (float)w->height();

    bool tdlb_show[6] = {false};

    memcpy(tdlb_show, pageErrorTest->digi_tdlb_show, sizeof(tdlb_show));

    if(isFt3)
    {
        //ft3 ========================================================
        float dblScaling_X, dblScaling_Y;		// X轴和Y轴的缩放比例
        double m_iShuZiLiangMax=0;
        m_iShuZiLiangMax = udp->getMaxPointValue_Bc();

        if (m_iShuZiLiangMax == 0.0)
            m_iShuZiLiangMax = 1;

        for(int i = 0; i < 6; i++)
        {
            if(! tdlb_show[i])
            {
                continue;
            }
            switch(i)
            {
                case 0:
                    painter.setPen(Qt::yellow);
                    break;
                case 1:
                    painter.setPen(Qt::green);
                    break;
                case 2:
                    painter.setPen(Qt::red);
                    break;
                case 3:
                    painter.setPen(Qt::darkYellow);
                    break;
                case 4:
                    painter.setPen(Qt::darkGreen);
                    break;
                case 5:
                    painter.setPen(Qt::darkRed);
                    break;
                default:
                    painter.setPen(Qt::gray);
                    break;
            }

            //dblScaling_Y = dblHeight / ( udp->maxFt3_inChannel[i] * 4.0 + 0.1);
            dblScaling_Y = dblHeight / 400;

            int iArrLen = 3 * udp->ft3SamplesPerCycle();

            dblScaling_X = dblWidth / ((float)iArrLen - 1);

            qDebug()<<"Now, pinat info"<<iArrLen<<dblScaling_Y<<dblScaling_X;

            showArray = &((*udp->showArray_ft3)[i]);

            for(int j = 0; j < iArrLen - 1; j++)
            {
                beginPoint.setX(dblScaling_X * (float)j);
                beginPoint.setY(dblHeight / 2 - (*showArray)[j] * dblScaling_Y-100);
                endPoint.setX(dblScaling_X * (float)(j+1) );
                endPoint.setY(dblHeight / 2 - (*showArray)[j+1] * dblScaling_Y-100);
                painter.drawLine( beginPoint, endPoint );

                qDebug()<<"simple value="<<(*showArray)[j]<<i;
            }
        }
    }
    else
    {
        //9-2 ========================================================
        float dblScaling_X, dblScaling_Y;		// X轴和Y轴的缩放比例
        double m_iShuZiLiangMax=0;
        m_iShuZiLiangMax = cappacket->getMaxShuZiLiang();

        if (m_iShuZiLiangMax == 0.0)
            m_iShuZiLiangMax = 1;

        for(int i = 0; i < 6; i++)
        {
            if(!tdlb_show[i]) continue;

            switch(i)
            {
                case 0:
                    painter.setPen(Qt::yellow);
                    break;
                case 1:
                    painter.setPen(Qt::green);
                    break;
                case 2:
                    painter.setPen(Qt::red);
                    break;
                case 3:
                    painter.setPen(Qt::darkYellow);
                    break;
                case 4:
                    painter.setPen(Qt::darkGreen);
                    break;
                case 5:
                    painter.setPen(Qt::darkRed);
                    break;
                default:
                    painter.setPen(Qt::gray);
                    break;
            }

            dblScaling_Y = dblHeight / ( cappacket->maxValueMu[i] * 4.0);

            int iArrLen = 4 * cappacket->SmpRate();

            dblScaling_X = dblWidth / ((float)iArrLen - 1);

            qDebug()<<"Now, pait for channel "<< cappacket->maxValueMu[i];

            showArray = &((*cappacket->mu_showArray)[i]);

            for(int j = 0; j < iArrLen-1; j++)
            {
                beginPoint.setX(dblScaling_X * (float)j);
                beginPoint.setY(dblHeight / 2 - (*showArray)[j] * dblScaling_Y-100);
                endPoint.setX(dblScaling_X * (float)(j+1) );
                endPoint.setY(dblHeight / 2 - (*showArray)[j+1] * dblScaling_Y-100);
                painter.drawLine( beginPoint, endPoint );
            }
        }
    }

    //udp ============================================================
    float dblScaling_X_udp, dblScaling_Y_udp;
    double SampleMax_udp = 0;

    SampleMax_udp = udp->dblSampleMax_udp;

    for(int i = 0; i < 6; i++)
    {
        if(! tdlb_show[i])
        {
            continue;
        }

        switch(i)
        {
            case 0:
                painter.setPen(Qt::yellow);
                break;
            case 1:
                painter.setPen(Qt::green);
                break;
            case 2:
                painter.setPen(Qt::red);
                break;
            case 3:
                painter.setPen(Qt::darkYellow);
                break;
            case 4:
                painter.setPen(Qt::darkGreen);
                break;
            case 5:
                painter.setPen(Qt::darkRed);
                break;
            default:
                painter.setPen(Qt::gray);
                break;
        }

        dblScaling_Y_udp = dblHeight / ( udp->maxValueStd[i] * 4.0 + 0.00000000001);

        painter.setPen(Qt::white);

        showArray_udp = &((*udp->showArray)[i]);

        int iArrLen = 4 * 80;

        dblScaling_X_udp = dblWidth / ((float)iArrLen - 1.0);

        for(int j = 0; j < iArrLen-1; j++)
        {
            beginPoint.setX(dblScaling_X_udp * (float)j);
            beginPoint.setY(dblHeight / 2 - (*showArray_udp)[j] * dblScaling_Y_udp-100);
            endPoint.setX(dblScaling_X_udp * (float)(j+1) );
            endPoint.setY(dblHeight / 2 - (*showArray_udp)[j+1] * dblScaling_Y_udp-100);
            painter.drawLine( beginPoint, endPoint );
        }
    }
}

void MainWindow::paintonSZB(QWidget *w)
{
    qDebug()<<"paintSZB......";

    QPainter painter(w);
    painter.translate(0,100);
    painter.drawLine(0,0,800,0);

    QPoint beginPoint;
    QPoint endPoint;

    double (*showArray)[10*256];

    QCheckBox *paintEnabled[6];
    paintEnabled[0] = pageBwjy->enableUA;
    paintEnabled[1] = pageBwjy->enableUB;
    paintEnabled[2] = pageBwjy->enableUC;
    paintEnabled[3] = pageBwjy->enableIA;
    paintEnabled[4] = pageBwjy->enableIB;
    paintEnabled[5] = pageBwjy->enableIC;

    float dblWidth, dblHeight;
    dblWidth = (float)w->width();
    dblHeight = (float)w->height();

    float dx = dblWidth/240.0;
    float dy = 0;

    for(int i=0; i<6; i++)
    {
        if(!paintEnabled[i]->isChecked()) continue;

        showArray = &((*cappacket->mu_showArray)[i]);

        dy = dblHeight / (cappacket->maxInChannel[i] * 3);

        qDebug()<<"paintOnszb, maxInChannnel"<<i<<cappacket->maxInChannel[i];

        switch(i)
        {
            case 0:
                painter.setPen(Qt::yellow);
                break;
            case 1:
                painter.setPen(Qt::green);
                break;
            case 2:
                painter.setPen(Qt::red);
                break;
            case 3:
                painter.setPen(Qt::darkYellow);
                break;
            case 4:
                painter.setPen(Qt::darkGreen);
                break;
            case 5:
                painter.setPen(Qt::darkRed);
                break;
            default:
                painter.setPen(Qt::gray);
                break;
        }

        for(int j = 0; j < 240; j++)
        {
            beginPoint.setX(dx * (float)j);
            beginPoint.setY(dblHeight / 2 - (*showArray)[j] * dy-100);
            endPoint.setX(dx * (float)(j+1) );
            endPoint.setY(dblHeight / 2 - (*showArray)[j+1] * dy-100);
            painter.drawLine( beginPoint, endPoint );
            //qDebug()<<"simple value="<<cappacket->m_PointArray[i][m_iStartPoint+j];
        }
    }

    double sample, sample_last = 0;
    painter.setPen(Qt::white);
    for(int j = 0; j < 80; j++)
    {
        sample = cappacket->maxInChannel[5] * sin( (j+1) * 2 * PI/80.0);

        beginPoint.setX(dx * (float)j);
        beginPoint.setY(dblHeight / 2 - sample_last * dy-100);
        endPoint.setX(dx * (float)(j+1) );
        endPoint.setY(dblHeight / 2 - sample * dy-100);
        painter.drawLine( beginPoint, endPoint );

        sample_last = sample;
    }

    beginPoint.setX(dx*80);
    beginPoint.setY(dblHeight/2-100);

    endPoint.setX(dx*240);
    endPoint.setY(dblHeight/2-100);

    painter.drawLine(beginPoint, endPoint);
}


void MainWindow::udpCmd(char type)
{
    int ilen=pageConfig->getUdpMutLen();

    cUdpSend=(char*)malloc(ilen);

    pageConfig->getsendUdp_mut(cUdpSend, type);   //mu 精度测试

    udp->UdpSendByte(cUdpSend,ilen);

    if(type == 0) // reset
    {
        udp->setRead(false);
    }
    else
    {
        udp->setRead(true);
    }
}

void MainWindow::showAll()
{
    int iTestMode = 3;

    static int try_to_open = 2;

    cappacket->setTestType(iTestMode);

    //memcpy( pageErrorTest->pageAll->channelMapping, pageConfig->channelMapping,sizeof(pageConfig->channelMapping));

    pageErrorTest->pageAll->updateChnlMapping();

    if (!cappacket->IsOpen())
    {
        if(try_to_open--)
        {
            cappacket->Open(1);

            QTimer::singleShot(500, this, SLOT(showAll()));

            qDebug()<<"Try to open the port,"<<try_to_open;

            return;
        }
        else
        {
            try_to_open = 2;

            qDebug()<<"读取9-2报文失败，请检查网络连接后重试！";

            showInfo("读取9-2报文失败，请检查网络连接后重试！");
        }
    }
    else
    {
        qDebug()<<"the port is open!";

        try_to_open = 2;

        setCSCS(iTestMode);

        for(int i=0;i<12;i++)
           cappacket->SetChannelShow(i,true);

        cappacket->StopCap(false);

        cappacket->start();

        showControlFlag = 3;
    }
}

void MainWindow::settempbuff()
{
    qDebug()<<"samples is ready"<<showControlFlag;

    pageErrorTest->pageAll->update();

    pageLubo->paintArea->update();
}

void MainWindow::paintOnAll(QWidget *w)
{
  //  if (!cappacket->getIsOK())
  //      return;
  //  cappacket->StopCap(true);
    QPainter painter(w);
    QPoint beginPoint;
    QPoint endPoint;
    painter.translate(0,100);
    painter.drawLine(0,0,800,0);

    float dblWidth, dblHeight;
    dblWidth = (float)w->width();
    dblHeight = (float)w->height();
 //   int iPoints;		// 点数
    float dblScaling_X, dblScaling_Y;		// X轴和Y轴的缩放比例
    double m_iShuZiLiangMax=0;
    m_iShuZiLiangMax=cappacket->getMaxShuZiLiang();
   // m_iShuZiLiangMax=cappacket->getMaxShuZiLiang();
    if (m_iShuZiLiangMax==0.0)
        return;
//    double m_dblFuZhi=dblFuZhi_HGQ;
    //double dblFZ=(double)m_iShuZiLiangMax / (double)m_dblFuZhi;
//    if(dblMaxBFB < dblFZ)
//        dblMaxBFB = dblFZ;
//    dblMaxBFB += 0.05;

     if(m_iShuZiLiangMax != 0)
        dblScaling_Y = dblHeight / (m_iShuZiLiangMax * 3);
    else
        dblScaling_Y = 0;
//    if (iTestMode==2)getChannelMU
//        m_dblShowPeriods=cappacket->ZhouQi();
    for(int i = 0; i < 12; i++)
    {
        if(cappacket->GetChannelShow(i))
        {
            switch(i)
            {
                case 0:
                        painter.setPen(QColor(0X00,0X80,0X00));
                        break;
                case 1:
                        painter.setPen(QColor(0X80,0X80,0X00));
                        break;
                case 2:
                        painter.setPen(QColor(0X00,0X00,0X80));
                        break;
                case 3:
                        painter.setPen(QColor(0X80,0X00,0X80));
                        break;
                case 4:
                        painter.setPen(QColor(0X00,0X80,0X80));
                        break;
                case 5:
                        painter.setPen(QColor(0X80,0X80,0X80));
                        break;
                case 6:
                        painter.setPen(QColor(0XC0,0XC0,0XC0));
                        break;
                case 7:
                        painter.setPen(QColor(0XFF,0X00,0X00));
                        break;
                case 8:
                        painter.setPen(QColor(0X00,0XFF,0X00));
                        break;
                case 9:
                        painter.setPen(QColor(0XFF,0XFF,0X00));
                        break;
                case 10:
                        painter.setPen(QColor(0X00,0X00,0XFF));
                        break;
                case 11:
                        painter.setPen(QColor(0XFF,0X00,0XFF));
                        break;
                default:
                        painter.setPen(Qt::red);
                        break;
            }

            int iArrLen =  cappacket->SmpRate();
            dblScaling_X = dblWidth / ((float)iArrLen - 1);
            for(int j = 0; j < iArrLen-1; j++)
            {
                beginPoint.setX(dblScaling_X * (float)j);
                beginPoint.setY(dblHeight / 2 - cappacket->m_PointArray[i][j] * dblScaling_Y-100);
                endPoint.setX(dblScaling_X * (float)(j+1) );
                endPoint.setY(dblHeight / 2 - cappacket->m_PointArray[i][j+1] * dblScaling_Y-100);
                painter.drawLine( beginPoint, endPoint );
            }

            pageErrorTest->pageAll->subPages[i]->setMaxMag(cappacket->maxSampleInChannel[i]);
        }
    }
}

void MainWindow::paintOnLubo(QWidget *w)
{
    qDebug()<<"paint on lubo...";

    QPainter painter(w);
    QPoint beginPoint;
    QPoint endPoint;
    painter.translate(0,100);
    painter.drawLine(0,0,800,0);

    float dblWidth, dblHeight;
    dblWidth = (float)w->width();
    dblHeight = (float)w->height();

    float dblScaling_X, dblScaling_Y;		// X轴和Y轴的缩放比例

    double m_iShuZiLiangMax=0;
    m_iShuZiLiangMax=cappacket->getMaxShuZiLiang();

    if (m_iShuZiLiangMax==0.0)
        m_iShuZiLiangMax = 0.005;

     if(m_iShuZiLiangMax != 0)
        dblScaling_Y = dblHeight / (m_iShuZiLiangMax * 3);
    else
        dblScaling_Y = 0;

     qDebug()<<"y axis:"<<m_iShuZiLiangMax<<dblScaling_Y;

    for(int i = 0; i < 12; i++)
    {
        if(cappacket->GetChannelShow(i))
        {
            switch(i)
            {
                case 0:
                        painter.setPen(QColor(0X00,0X80,0X00));
                        break;
                case 1:
                        painter.setPen(QColor(0X80,0X80,0X00));
                        break;
                case 2:
                        painter.setPen(QColor(0X00,0X00,0X80));
                        break;
                case 3:
                        painter.setPen(QColor(0X80,0X00,0X80));
                        break;
                case 4:
                        painter.setPen(QColor(0X00,0X80,0X80));
                        break;
                case 5:
                        painter.setPen(QColor(0X80,0X80,0X80));
                        break;
                case 6:
                        painter.setPen(QColor(0XC0,0XC0,0XC0));
                        break;
                case 7:
                        painter.setPen(QColor(0XFF,0X00,0X00));
                        break;
                case 8:
                        painter.setPen(QColor(0X00,0XFF,0X00));
                        break;
                case 9:
                        painter.setPen(QColor(0XFF,0XFF,0X00));
                        break;
                case 10:
                        painter.setPen(QColor(0X00,0X00,0XFF));
                        break;
                case 11:
                        painter.setPen(QColor(0XFF,0X00,0XFF));
                        break;
                default:
                        painter.setPen(Qt::red);
                        break;
            }
            int iArrLen = m_dblShowPeriods * cappacket->SmpRate();

            dblScaling_X = dblWidth / ((float)iArrLen - 1);
            for(int j = 0; j < iArrLen-1; j++)
            {
                beginPoint.setX(dblScaling_X * (float)j);
                beginPoint.setY(dblHeight / 2 - cappacket->m_PointArray[i][m_iStartPoint+j] * dblScaling_Y-100);
                endPoint.setX(dblScaling_X * (float)(j+1) );
                endPoint.setY(dblHeight / 2 - cappacket->m_PointArray[i][m_iStartPoint+j+1] * dblScaling_Y-100);
                painter.drawLine( beginPoint, endPoint );
            }
        }
    }

    pageLubo->txtLubo->setText(cappacket->AnalyseResult());
    cappacket->StopCap(true);
    pageLubo->btnLuboData->setEnabled(true);

    pageLubo->btnStart->setText("开始");
//    if(m_bIsConn)
//          tcpServer->TcpSend("3a:" + cappacket->AnalyseResult());

}

void MainWindow::changeShowPage()
{
    qDebug()<<"set test channel"<<pageErrorTest->pageAll->subPages[0]->getIndex();

    cappacket->setTestChannel(pageErrorTest->pageAll->subPages[0]->getIndex());
}

void MainWindow::slotBack()
{
    qDebug()<<"slotBack(), back to main...";

    if(pageErrorTest->btnBack->text() == "完成") //source
    {
        if(pageErrorTest->btnStart->text() == "停止")
        {
            showInfo("正在应用源配置...");

            pageErrorTest->sourcePage->stopSrc();

            //sleep
            QElapsedTimer sleep_timer;
            sleep_timer.start();
            while(sleep_timer.elapsed() < 600)
            {
                QCoreApplication::processEvents();
            }

            /*sleep2
            QEventLoop eventloop;
            QTimer::singleShot(500, &eventloop, SLOT(quit()));
            eventloop.exec();
            */

            pageErrorTest->sourcePage->startSrc();

            source_has_been_reconfiged = 0;
        }
    }
    else //if(pageErrorTest->btnBack->text() == "完成")
    {
        showPara();

        if(pageErrorTest->btnStart->text() == "停止")
        {
            NetTest_mu();
        }
        else
        {
            cappacket->StopCap(true);

            if (cappacket->IsOpen())
                cappacket->Close();
        }
    }
}

void MainWindow::analyzeHarmonic()
{
    int i=0;
    fftw_complex *out;
    harmonic_std_total = 0;
    harmonic_dut_total = 0;

    int channel_index = pageErrorTest->harmonicAnalyze->cboChannel->currentIndex();
    double *data;
    QTime time_count;

    time_count.start();
    out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * 320);
    //data = *(udp->showArray)[channel_index];
    data = &((*udp->showArray)[channel_index][0]);
    fftw_plan p1 = fftw_plan_dft_r2c_1d( 320, data, out, FFTW_ESTIMATE);
    fftw_execute(p1);

    for(i=0; i < 4 *41 + 1;)
    {
        int index = i / 4;
        harmonic_std[index] = sqrt(out[i][0]*out[i][0] + out[i][1]*out[i][1])/160/1.414;
        qDebug()<<"rms std:"<<index<<QString::number( harmonic_std[index], 'f', 4);
        harmonic_std_total += harmonic_std[index];
        i = i + 4;
    }

    qDebug()<<"fftw3 time cost:"<<time_count.elapsed();
    //data = *(cappacket->mu_showArray)[channel_index];
    data = &((*cappacket->mu_showArray)[channel_index][0]);
    fftw_plan p2 = fftw_plan_dft_r2c_1d( 320, data, out, FFTW_ESTIMATE);
    fftw_execute(p2);

    for(i=0; i < 4 *41 + 1;)
    {
        int index = i / 4;
        harmonic_dut[index] = sqrt(out[i][0]*out[i][0] + out[i][1]*out[i][1])/160/1.414;
        qDebug()<<"rms dut:"<<index<<QString::number( harmonic_dut[index], 'f', 4);
        harmonic_dut_total += harmonic_dut[index];
        i = i + 4;
    }
    fftw_free(out);
}

void MainWindow::paintHarmonic()
{
    int order = pageErrorTest->harmonicAnalyze->harmonicOrder->currentIndex() + 2;

    pageErrorTest->harmonicAnalyze->calError(harmonic_std[order], harmonic_dut[order]);

    QCPBars *thePlot = (QCPBars *)pageErrorTest->harmonicAnalyze->harmonicPlot->plottable();

    QVector<QCPBarsData> *mData = thePlot->data()->coreData();

    mData->clear();
    QCPBarsData newPoint;
    for(int i = 0; i < 42; i++)
    {
        harmonic_std[i] = ( harmonic_std[i] * 100) / harmonic_std_total;
        harmonic_dut[i] = ( harmonic_dut[i] * 100) / harmonic_dut_total;

        newPoint.key = i;
        newPoint.value = (pageErrorTest->harmonicAnalyze->btnSelectStd->isChecked()? harmonic_std[i]: harmonic_dut[i]);

        mData->append(newPoint);
    }
    pageErrorTest->harmonicAnalyze->harmonicPlot->rescaleAxes();
    pageErrorTest->harmonicAnalyze->harmonicPlot->yAxis->setRange(0, 105);
    pageErrorTest->harmonicAnalyze->harmonicPlot->xAxis->setRange(0, 42);
    pageErrorTest->harmonicAnalyze->harmonicPlot->replot();
    harmonic_std[0] = 100 - harmonic_std[1] - harmonic_std[0];
    harmonic_dut[0] = 100 - harmonic_dut[1] - harmonic_dut[0];

    for(int i=0; i < 42; i++)
    {
        QTableWidgetItem *cubesItem;
        if(pageErrorTest->harmonicAnalyze->btnSelectStd->isChecked())
        {
            cubesItem = new QTableWidgetItem(QString::number(harmonic_std[i], 'f', 2));
        }
        else
        {
            cubesItem = new QTableWidgetItem(QString::number(harmonic_dut[i], 'f', 2));
        }
        cubesItem->setTextAlignment(Qt::AlignCenter);
        pageErrorTest->harmonicAnalyze->harmonicTable->setItem(1,i,cubesItem );
    }
}

void MainWindow::bwTest()
{
    if (pageBwjy->btnStart->text()=="停止")
    {
        pageBwjy->btnStart->setText(tr("开始"));

        pageErrorTest->sourcePage->stopSrc();

        udp->UdpSendCmd("stop",6);

        udp->setRead(false);

        return;
    }

    showInfo("该测试，需将报文接入光口 3 ！");

    QElapsedTimer sleep_timer;
    sleep_timer.start();
    while(sleep_timer.elapsed() < 1000)
    {
        QCoreApplication::processEvents();
    }

    if (pageBwjy->tabWidget->currentIndex() == 2) //首周波
    {
        QString style_red="background-color: red; border-radius:3px;";

        pageBwjy->labResutUA->setStyleSheet(style_red);
        pageBwjy->labResutUB->setStyleSheet(style_red);
        pageBwjy->labResutUC->setStyleSheet(style_red);
        pageBwjy->labResutIA->setStyleSheet(style_red);
        pageBwjy->labResutIB->setStyleSheet(style_red);
        pageBwjy->labResutIC->setStyleSheet(style_red);

        pageBwjy->labResutUA->setText("未对齐");
        pageBwjy->labResutUB->setText("未对齐");
        pageBwjy->labResutUC->setText("未对齐");
        pageBwjy->labResutIA->setText("未对齐");
        pageBwjy->labResutIB->setText("未对齐");
        pageBwjy->labResutIC->setText("未对齐");

        double StandVoltage = pageConfig->voltagePre* 1000;
        if(pageConfig->voltageStdIndex == 1)
        {
            StandVoltage = StandVoltage * 0.5773505;
        }
        double StandCurrent = pageConfig->currentPre;

        cappacket->maxValueMu[0]=cappacket->maxValueMu[1]=cappacket->maxValueMu[2]=StandVoltage;
        cappacket->maxValueMu[3]=cappacket->maxValueMu[4]=cappacket->maxValueMu[5]=StandCurrent;

        //call cappacket begin szb
        cappacket->StopCap(false);

        bool openNetFlag=cappacket->Open(1);

        if(!openNetFlag)
        {
            showInfo(tr("未检测到 9-2 报文！"));
            return;
        }

        for(int i = 0; i < 6; i++)
        {
            cappacket->setChannelMU(i, channelMapping[i]);
        }

        cappacket->setTestType('S');

        cappacket->start();

        showControlFlag = 'S';

        //udpCmd('B');

        //tell the source begin szb
        QByteArray cmd_start;
        cmd_start[0] = '*';
        cmd_start[1] = 0x00;
        cmd_start[2] = 0x01;

        pageErrorTest->sourcePage->feedback(cmd_start);
    }
    else if (pageBwjy->tabWidget->currentIndex()==0)      //报文离散度
    {
      //  cappacket->setiType(1);
        pageBwjy->txtYs->setText("");
        pageBwjy->txtMaxYs->setText("");
        pageBwjy->txtMinYs->setText("");
        pageBwjy->txtAvgYs->setText("");
        pageBwjy->txtMaxJg->setText("");
        pageBwjy->txtMinJg->setText("");

        pageBwjy->txtBwAll->setText("");
        pageBwjy->txtBwLost->setText("");
        pageBwjy->txtBwError->setText("");
        m_iDelayNum=0;
        delayMin=0;
        delayMax=0;
        delayAvg=0;
        lsMin=0;
        lsMax=0;
        m_dblBwAll=0;
        m_iBwLost=0;
        m_iBwError=0;
        iYsNum=0;
        QString s=pageBwjy->cboTime->currentText();
        int iwz=s.indexOf("*");
        if (iwz>=0)
        {
            s=s.left(iwz);
            iYsNum=s.toInt()*60*60;
        }
        else
        {
            iYsNum=s.toInt()*60;
        }
        ysTimer->start(1000);

        udp->UdpSendCmd("start",6);

        udp->setRead(true);

        udpCmd(0);
    }
    else if(pageBwjy->tabWidget->currentIndex()==1)      //对时守时测量
    {
        //when get ds_error from SMV packets, set iNetPort to light-2
        pageBwjy->txtDs->setText("0.000");
        pageBwjy->txtMaxDs->setText("0.000");
        pageBwjy->txtSs->setText("0.000");
        pageBwjy->txtMaxSs->setText("0.000");

        if(pageBwjy->beginDsTesting->isChecked())
        {
            switch(pageBwjy->combTestingTime->currentIndex())
            {
            case 0:
                    iDsNum = 10;break;
            case 1:
                    iDsNum = 30;break;
            case 2:
                    iDsNum = 60;break;
            case 3:
                    iDsNum = 600;break;
            case 4:
                    iDsNum = 3600;break;
            default:
                    iDsNum = 0;break;
            }
        }
        else
        {
            switch(pageBwjy->combTestingTime->currentIndex())
            {
            case 0:
                    iDsNum = 300;break;
            case 1:
                    iDsNum = 600;break;
            case 2:
                    iDsNum = 1800;break;
            case 3:
                    iDsNum = 3600;break;
            case 4:
                    iDsNum = 24*3600;break;
            default:
                    iDsNum = 0;
            }
        }
//        iDsNum= newBwjyPage->txtDsTime->text().toInt();
//        iSsNum= newBwjyPage->txtSsTime->text().toInt();
        dsMax=0;
        ssMax=0;
        dds=0;
        dsstemp=0;
        iDsFlag=0; //0 对时,1 守时

        if (iDsNum<=0)
        {
            QMessageBox::information(NULL,"错误","time is undefined！");
            return;
        }

        iDsNum_static = iDsNum;

        iDsNum = 0;

        dsTimer->start(1000); // refresh the displayed result per second

        //udpCmd('B');

        udp->UdpSendCmd("start",6);

        udp->setRead(true);
    }

    pageBwjy->btnStart->setText("停止");
}

void MainWindow::bwjy_pageChanged()
{
    if(pageBwjy->btnStart->text() == "停止")
    {
        pageBwjy->btnStart->setText(tr("开始"));

        pageErrorTest->sourcePage->stopSrc();

        udpCmd(0);

        udp->UdpSendCmd("stop",5);

        udp->setRead(false);
    }
}

void MainWindow::szbSlot()
{

    QString style_blue="background-color: blue; border-radius:3px;";

    if(cappacket->szb_found[0])
    {
        pageBwjy->labResutUA->setStyleSheet(style_blue);
        pageBwjy->labResutUA->setText("已对齐");
    }

    if(cappacket->szb_found[1])
    {
        pageBwjy->labResutUB->setStyleSheet(style_blue);
        pageBwjy->labResutUB->setText("已对齐");
    }

    if(cappacket->szb_found[2])
    {
        pageBwjy->labResutUC->setStyleSheet(style_blue);
        pageBwjy->labResutUC->setText("已对齐");
    }

    if(cappacket->szb_found[3])
    {
        pageBwjy->labResutIA->setStyleSheet(style_blue);
        pageBwjy->labResutIA->setText("已对齐");
    }

    if(cappacket->szb_found[4])
    {
        pageBwjy->labResutIB->setStyleSheet(style_blue);
        pageBwjy->labResutIB->setText("已对齐");
    }

    if(cappacket->szb_found[5])
    {
        pageBwjy->labResutIC->setStyleSheet(style_blue);
        pageBwjy->labResutIC->setText("已对齐");
    }

    pageBwjy->paintArea->update();
}

void MainWindow::showDelayText()
{
    double m_yanshi=udp->getYanshi();
    int m_min=udp->getJgMin();
   // qDebug()<<m_min;
    int m_max=udp->getJgMax();
    int m_bwall=udp->getbwAll();
    int m_bwlost=udp->getbwLost();
    int m_bwerror=udp->getbwError();
    //double m_avg=udp->getJgAvg();

    double error1 = udp->error1 / 100.0;
    double error2 = udp->error2 / 100.0;
    double error3 = udp->error3 / 100.0;
    double error4 = udp->error4 / 100.0;

    m_iDelayNum++;
    if (m_iDelayNum==1)
    {
        delayMin=m_yanshi;
        delayMax=m_yanshi;
        lsMin=m_min;
        lsMax=m_max;
        m_dblBwAll=m_bwall;
        m_iBwLost=m_bwlost;
        m_iBwError=m_bwerror;
    }
    else
    {
        if (m_yanshi>delayMax)
            delayMax=m_yanshi;
        if(m_yanshi<delayMin)
            delayMin=m_yanshi;
        if (m_max>lsMax)
            lsMax=m_max;
        if (m_min<lsMin)
            lsMin=m_min;
        m_dblBwAll += m_bwall;
        m_iBwLost += m_bwlost;
        m_iBwError += m_bwerror;
    }
    delayAvg +=m_yanshi;

    pageBwjy->txtYs->setText(QString::number(m_yanshi/10,'f',1));
    pageBwjy->txtMaxYs->setText(QString::number(delayMax/10,'f',1));
    pageBwjy->txtMinYs->setText(QString::number(delayMin/10,'f',1));
    pageBwjy->txtAvgYs->setText(QString::number((delayAvg/m_iDelayNum)/10,'f',1));
    pageBwjy->txtMaxJg->setText(QString::number((float)lsMax/10,'f',1));
    pageBwjy->txtMinJg->setText(QString::number(lsMin/10,'f',1));
    //newBwjyPage->txtBwAll->setText(QString::number(m_dblBwAll,''));
    pageBwjy->txtBwAll->setText(QString::number(m_bwall,10));
    pageBwjy->txtBwLost->setText(QString::number(m_bwlost));
    pageBwjy->txtBwError->setText(QString::number(m_bwerror));

    pageBwjy->txterror1->setText(QString::number(error1,'f',2));
    pageBwjy->txterror2->setText(QString::number(error2,'f',2));
    pageBwjy->txterror3->setText(QString::number(error3,'f',2));
    pageBwjy->txterror4->setText(QString::number(error4,'f',2));

    //test commit
//    if (m_bIsConn)
//    {
//        QString s="4a:";

//        s += ":" + newBwjyPage->txtBwAll->text();
//        s += ":" + newBwjyPage->txtBwLost->text();
//        s += ":" + newBwjyPage->txtBwError->text();

//        s += ":" + newBwjyPage->txterror1->text();
//        s += ":" + newBwjyPage->txterror2->text();
//        s += ":" + newBwjyPage->txterror3->text();
//        s += ":" + newBwjyPage->txterror4->text();

//        tcpServer->TcpSend(s);
//    }
}

void MainWindow::slotDs()
{
    QString strInfo="";

    double dss;
    static double tmp;

    static int error_times = 0;

    if (iDsNum < iDsNum_static) // if iDsNum do not reach the testing-time
    {
        iDsNum++;

        if((iDsNum) < 5) // in first 5 seconds, do nothing
        {
            pageBwjy->labInfoDs->setText("数据采集中...");

            jdys_avg = udp->getDs();

            dsMax = jdys_avg - tmp;

            tmp = udp->getDs();

            error_times = 0;

            return;
        }

        // jdys = time_delay
        // delta(time_delay) = jdys - jdys_old
        // 1s_packet = 1s_stand + delta(time_delay)
        // wc_packet = 1s_packet - 1s_stand = delta(time_delay)
        if( pageBwjy->beginDsTesting->isChecked() )
        {
            strInfo = tr("正在测试对时误差,剩余 ");

            jdys_avg = jdys_avg * (iDsNum - 1)/iDsNum + tmp/iDsNum;

            dds = tmp - jdys_avg; // the true-value is avg of sample

            if(fabs(dds) - fabs(dsMax) > 500) // if the dds is too large, abort it
            {
                error_times ++;

                if( error_times == 5)
                {
                    dsTimer->stop();
                    strInfo = tr("出现错误,请重新开始测试!");
                    error_times = 0;
                    udpCmd(0);

                    udp->UdpSendCmd("stop",5);
                }

                return;
            }
        }
        else
        {
            strInfo=tr("正在测试守时误差,剩余 ");

            dds = tmp - jdys_avg;

            if(fabs(dds) - fabs(dsMax) > 100) // if the dds is too large, abort it
            {
                error_times ++;

                if( error_times == 5)
                {
                    dsTimer->stop();
                    strInfo=tr("出现错误,请重新开始测试!");
                    pageBwjy->labInfoDs->setText(strInfo);
                    error_times = 0;
                    udpCmd(0);

                    udp->UdpSendCmd("stop",5);
                }

                return;
            }
        }

        tmp = udp->getDs();

        strInfo+=QString::number(iDsNum_static - iDsNum);
        strInfo+=tr(" 秒");

        if(fabs(dds) > fabs(dsMax))
        {
            dsMax = dds;
        }

        if(pageBwjy->beginDsTesting->isChecked())
        {
            pageBwjy->labCurrentJDYS->setText(QString::number(jdys_avg+dds,'f',3));
            // newBwjyPage->labCurrentJDYS_avg->setText(QString::number(jdys_avg,'f',3));
            pageBwjy->labCurrentJDYS_avg->setText(QString::number(udp->delay_specified,'f',3));
            pageBwjy->txtDs->setText(QString::number(dds,'f',3));
            pageBwjy->txtMaxDs->setText(QString::number(dsMax,'f',3));
        }
        else
        {
            pageBwjy->labCurrentJDYS->setText(QString::number(jdys_avg+dds,'f',3));
            pageBwjy->txtSs->setText(QString::number(dds,'f',3));
            pageBwjy->txtMaxSs->setText(QString::number(dsMax,'f',3));
        }

//        if (m_bIsConn)          //联机时上传误差数据;
//        {
//            QString s="4b:";
//            s += pageBwjy->labCurrentJDYS->text();
//            s += ":";
//            s += pageBwjy->labCurrentJDYS_avg->text();
//            s += ":";
//            s += pageBwjy->txtDs->text();
//            s += ":";
//            s += pageBwjy->txtMaxDs->text();
//            s += ":";
//            s += pageBwjy->txtSs->text();
//            s += ":";
//            s += pageBwjy->txtMaxSs->text();

//            tcpServer->TcpSend(s);
//        }
    }
    else// if (iDsNum==iDsNum_static) // duishi testing is over
    {
      //  iDsNum--;
        if (dsMax==0.0)
        {
            strInfo=tr("测试结果异常！测量结束");
        }
        else
        {
            strInfo=tr("测试结束");
        }

        dds = 0;
        dsMax = 0;
        error_times = 0;
        dsTimer->stop();
        pageBwjy->btnStart->setText(tr("开始"));
        showInfo(strInfo);
        udpCmd(0);

        udp->UdpSendCmd("stop",5);
    }

    pageBwjy->labInfoDs->setText(strInfo);
    /*
    if(m_bIsConn)
    {
        QString s="3c";
        s += QString::number(dds,'f',3)+",";
        s += QString::number(dsMax,'f',3)+",";
        s += QString::number(std::abs(dss),'f',3)+",";
        s += QString::number(std::abs(ssMax),'f',3)+",";
        tcpServer->TcpSend(s);
    }
    */
}

void MainWindow::repaintSZB()
{
    pageBwjy->paintArea->update();
}

void MainWindow::slotLuboData()
{
    QDir toDir = QDir::currentPath();
    QString fa = "c:/model-2000/pcap";
    QString fileName="";
    fileName= QFileDialog::getOpenFileName(this, tr("open file"), fa, tr("pcap file(*.pcap)"));
    if (fileName=="")
    {
        qDebug()<<"打开录波文件失败!";
        return;
    }
    pageLubo->scrllCurve->setValue(0);
    pageLubo->scrllCurve->setMinimum(0);
    pageLubo->scrllCurve->setMaximum(0);
    pageLubo->tSlider->setValue(0);
    for(int i=0;i<12;i++)
       cappacket->SetChannelShow(i,true);
    cappacket->pcap_openFile(fileName);

    m_dblShowPeriods=cappacket->ZhouQi()*50;
    m_iPeriodCnt=cappacket->ZhouQi()*50;
    //ChangeX_Text();
    //pageLubo->txtLuboTime->setText(QString::number(cappacket->ZhouQi()));
    //iTestMode=2;

    showControlFlag = 'L';
    m_iStartPoint = 0;
}

void MainWindow::tTest()
{
    m_dblShowPeriods = m_iPeriodCnt + (double)pageLubo->tSlider->value() / (double)pageLubo->tSlider->maximum()
                                                                            * (1 - m_iPeriodCnt);
    double dblWeiZi;
    if(pageLubo->scrllCurve->maximum() != 0)
            dblWeiZi = (double)pageLubo->scrllCurve->value() / (double)pageLubo->scrllCurve->maximum();		// 滚动条位置
    else
            dblWeiZi = 0;
    if (m_iPeriodCnt == m_dblShowPeriods)
    {
            pageLubo->scrllCurve->setMaximum(0);
    }else
    {
            pageLubo->scrllCurve->setMaximum((m_iPeriodCnt - m_dblShowPeriods) * 4);
            if(pageLubo->scrllCurve->maximum() < 1)
                pageLubo->scrllCurve->setMaximum(1);
    }
    pageLubo->scrllCurve->setValue( dblWeiZi * pageLubo->scrllCurve->maximum());
    scrllCurveScroll();
}

void MainWindow::scrllCurveScroll()
{
    if (pageLubo->scrllCurve->maximum()!= 0)
    {
            double dblK = (m_iPeriodCnt - m_dblShowPeriods)/ (double)pageLubo->scrllCurve->maximum();
            m_iStartPoint = (double)pageLubo->scrllCurve->value() * dblK * cappacket->SmpRate();
    }else
            m_iStartPoint = 0;
    //ChangeX_Text();
    showLubo();
}

void MainWindow::showLubo()
{
    bool all_closed = true;

    ClickableLabel *labList[12];
    labList[0] = pageLubo->labColor1;
    labList[1] = pageLubo->labColor2;
    labList[2] = pageLubo->labColor3;
    labList[3] = pageLubo->labColor4;
    labList[4] = pageLubo->labColor5;
    labList[5] = pageLubo->labColor6;
    labList[6] = pageLubo->labColor7;
    labList[7] = pageLubo->labColor8;
    labList[8] = pageLubo->labColor9;
    labList[9] = pageLubo->labColor10;
    labList[10] = pageLubo->labColor11;
    labList[11] = pageLubo->labColor12;

    for(int i = 0; i < 12; i++)
    {
        if(labList[i]->isChecked())
        {
            all_closed = false;
            cappacket->SetChannelShow(i, true);
        }
        else
        {
            cappacket->SetChannelShow(i, false);
        }
    }

    if(all_closed)
            pageLubo->chkSelectAll->setChecked(false);

    pageLubo->paintArea->update();
}

void MainWindow::startLubo()
{
    qDebug()<<"btnStart clicked...";

    if(pageLubo->btnStart->text() == "停止")
    {
        pageLubo->btnStart->setText("开始");

        showControlFlag = -1;

        cappacket->StopCap(true);

        if (cappacket->IsOpen())
            cappacket->Close();

        pageLubo->btnLuboData->setEnabled(true);

        return;
    }

    //pageLubo->paintArea->update();

    int iTime = pageLubo->combLuboTime->currentIndex()+1;
    iTime = 1;
    pageLubo->combLuboTime->setCurrentIndex(0);
    pageLubo->btnLuboData->setEnabled(false);
    pageLubo->txtLuboTime->setText(QString::number(iTime));
    pageLubo->txtLubo->setText("");

    pageLubo->scrllCurve->setValue(0);
    pageLubo->scrllCurve->setMinimum(0);
    pageLubo->scrllCurve->setMaximum(0);
    pageLubo->tSlider->setValue(0);

    m_iPeriodCnt=iTime*50;
    m_dblShowPeriods = m_iPeriodCnt;
    m_iStartPoint = 0;

    cappacket->init();

    cappacket->SetCapParamater(TestChannel_LuBo,m_iPeriodCnt,0,11585);
    for(int i=0;i<12;i++)
       cappacket->SetChannelShow(i,true);

    bool openNetFlag=cappacket->Open(1);

    if(!openNetFlag)
    {
        showInfo(tr("未检测到 9-2 报文！"));
        return;
    }

    cappacket->pcap_lubo();

    cappacket->setTestType('2');          // cappacket->setTestType(2);          //录波

    cappacket->StopCap(false);

    cappacket->setIsOK(false);

    cappacket->start();

    showControlFlag = 'L';

    pageLubo->btnStart->setText("停止");
}

void MainWindow::saveConfig()
{
    QString sql;

    sql="update wcbc set ";
    sql += "bc='"+pageSystem->txtbc->text() +"'";
    sql += ",bc1='"+pageSystem->txtbc1->text() +"'";
    sql += ",bc2='"+pageSystem->txtbc2->text() +"'";
    sql += ",bc3='"+pageSystem->txtbc3->text() +"'";
    sql += ",jc='"+pageSystem->txtjc->text() +"'";
    sql += ",jc1='"+pageSystem->txtjc1->text() +"'";
    sql += ",jc2='"+pageSystem->txtjc2->text() +"'";
    sql += ",jc3='"+pageSystem->txtjc3->text() +"'";

    QString wz="";
    if (pageSystem->cboBzbc->currentIndex()==0)
       wz="00";
    else if (pageSystem->cboBzbc->currentIndex()==1)
       wz="11";
    else if (pageSystem->cboBzbc->currentIndex()==2)
       wz="04";
    else if (pageSystem->cboBzbc->currentIndex()==3)
       wz="14";
    else if (pageSystem->cboBzbc->currentIndex()==4)
       wz="24";
    else if (pageSystem->cboBzbc->currentIndex()==5)
       wz="44";
    else if (pageSystem->cboBzbc->currentIndex()==6)
       wz="05";
    else if (pageSystem->cboBzbc->currentIndex()==7)
       wz="15";
    else if (pageSystem->cboBzbc->currentIndex()==8)
       wz="25";
    else if (pageSystem->cboBzbc->currentIndex()==9)
       wz="45";
    else if (pageSystem->cboBzbc->currentIndex()==10)
       wz="22";
    else if (pageSystem->cboBzbc->currentIndex()==11)
       wz="33";
    sql += " where type='" + wz +"'";

    QSqlQuery temp=myDB->openWcxxforSql(sql);
    temp.clear();

    sql ="update S_XTCS set ";
    sql+="cslx='0'";            //测量类型改为系统系数;
    sql+=",lubo_net_port='0'";            //测量类型改为系统比差系数;
    sql+=",lubo_zhouqi_cnt='0'";            //测量类型改为系统角差系数;
    sql+=",is_com_jyy='"+QString::number(pageSystem->cboDatatime->currentIndex())+"'";
    sql+=",bjcs='0'";

    QSqlQuery temp2=myDB->openWcxxforSql(sql);
    temp2.clear();

    showInfo(tr("数据已保存"));
}

void MainWindow::showBcdata()
{
    QString bzbc="00";

    if (pageSystem->cboBzbc->currentIndex()==0)
        bzbc="00";
    else if (pageSystem->cboBzbc->currentIndex()==1)
        bzbc="11";
    else if (pageSystem->cboBzbc->currentIndex()==2)
        bzbc="04";
    else if (pageSystem->cboBzbc->currentIndex()==3)
        bzbc="14";
    else if (pageSystem->cboBzbc->currentIndex()==4)
        bzbc="24";
    else if (pageSystem->cboBzbc->currentIndex()==5)
        bzbc="44";
    else if (pageSystem->cboBzbc->currentIndex()==6)
        bzbc="05";
    else if (pageSystem->cboBzbc->currentIndex()==7)
        bzbc="15";
    else if (pageSystem->cboBzbc->currentIndex()==8)
        bzbc="25";
    else if (pageSystem->cboBzbc->currentIndex()==9)
        bzbc="45";
    else if (pageSystem->cboBzbc->currentIndex()==10)
        bzbc="22";
    else if (pageSystem->cboBzbc->currentIndex()==11)
        bzbc="33";

    systemLoad(bzbc);
}

void MainWindow::systemLoad(QString bz)
{
    QSqlQuery tbWcbc=myDB->openWcxxforSql("select * from wcbc where type='"+ bz +"'");
    if (tbWcbc.next())
    {
        pageSystem->txtbc->setText(tbWcbc.value(7).toString());
        pageSystem->txtjc->setText(tbWcbc.value(8).toString());
        pageSystem->txtbc1->setText(tbWcbc.value(1).toString());
        pageSystem->txtjc1->setText(tbWcbc.value(2).toString());
        pageSystem->txtbc2->setText(tbWcbc.value(3).toString());
        pageSystem->txtjc2->setText(tbWcbc.value(4).toString());
        pageSystem->txtbc3->setText(tbWcbc.value(5).toString());
        pageSystem->txtjc3->setText(tbWcbc.value(6).toString());
    }
    else
    {
        pageSystem->txtbc->setText("0");
        pageSystem->txtjc->setText("0");
        pageSystem->txtbc1->setText("0");
        pageSystem->txtjc1->setText("0");
        pageSystem->txtbc2->setText("0");
        pageSystem->txtjc2->setText("0");
        pageSystem->txtbc3->setText("0");
        pageSystem->txtjc3->setText("0");
    }
    tbWcbc.clear();

    myDB->getXTCS();
    tbsx=myDB->m_Tbsx;
    pageSystem->cboDatatime->setCurrentIndex(tbsx);
}

void MainWindow::dataFirst()
{
    if (dataCount>0)
    {
        if(!tbWcxx.first())
     //       QMessageBox::information(NULL,tr("数据移动"),tr("已经是第一条了!"));
            showInfo(tr("已经是第一条了!"));
        else
            showWcdata();
    }
}

void MainWindow::dataPrevious()
{
    if (dataCount>0)
    {
        if(!tbWcxx.previous())
        {
        //    QMessageBox::information(NULL,tr("数据移动"),tr("已经是第一条了!"));
            showInfo(tr("已经是第一条了!"));
            tbWcxx.next();
        }
        else
            showWcdata();
    }
}

void MainWindow::dataNext()
{
    if (dataCount>0)
    {
        if(!tbWcxx.next())
        {
          //  QMessageBox::information(NULL,tr("数据移动"),tr("已经是最后一条了!"));
            showInfo(tr("已经是最后一条了!"));
            tbWcxx.previous();
        }
        else
            showWcdata();
    }
}

void MainWindow::dataLast()
{
    if (dataCount>0)
    {
        if(!tbWcxx.last())
            showInfo(tr("已经是最后一条了!"));
        //    QMessageBox::information(NULL,tr("数据移动"),tr("已经是最后一条了!"));
        else
            showWcdata();
    }
}

void MainWindow::showWcdata()
{
    QString datainfo="";
    datainfo=tr("第")+QString::number(tbWcxx.at()+1)+tr("条,");
    datainfo+=tr("共")+QString::number(dataCount)+tr("条记录");
    pageResult->labDataCount->setText(datainfo);

    pageResult->labRecordIndex->setText(tbWcxx.value(0).toString());
    pageResult->labRecordSyncMethod->setText(tbWcxx.value(1).toString());
    pageResult->labRecordStdInput->setText(tbWcxx.value(2).toString());
    pageResult->labRecordDut->setText(tbWcxx.value(3).toString());
    pageResult->labRecordStdValue->setText(tbWcxx.value(4).toString());
    pageResult->labRecordDate->setText(tbWcxx.value(5).toString());

    tbWcdata=myDB->openWcdata(tbWcxx.value(0).toString());

    pageResult->model->clear();
    pageResult->model->setColumnCount(6);
    pageResult->model->setHeaderData(0,Qt::Horizontal,tr("对象"));
    pageResult->model->setHeaderData(1,Qt::Horizontal,tr("百分点"));
    pageResult->model->setHeaderData(2,Qt::Horizontal,tr("标准有效值"));
    pageResult->model->setHeaderData(3,Qt::Horizontal,tr("被测有效值"));
    pageResult->model->setHeaderData(4,Qt::Horizontal,tr("比差(%)"));
    pageResult->model->setHeaderData(5,Qt::Horizontal,tr("角差(′)"));
//        newTestPage->tabWcData->setModel(newTestPage->model);
    pageResult->tabWcData->setColumnWidth(0,202);
    pageResult->tabWcData->setColumnWidth(1,100);
    pageResult->tabWcData->setColumnWidth(2,160);
    pageResult->tabWcData->setColumnWidth(3,160);
    pageResult->tabWcData->setColumnWidth(4,170);
    pageResult->tabWcData->setColumnWidth(5,170);
    //newTestPage->tabWcData->setColumnHidden(1,true);
    while (tbWcdata.next())
    {
        QStandardItem* item1=new QStandardItem();
        item1->setTextAlignment(Qt::AlignCenter);
        QStandardItem* item2=new QStandardItem();
        item2->setTextAlignment(Qt::AlignCenter);
        QStandardItem* item3=new QStandardItem();
        item3->setTextAlignment(Qt::AlignCenter);
        QStandardItem* item4=new QStandardItem();
        item4->setTextAlignment(Qt::AlignCenter);
        QStandardItem* item5=new QStandardItem();
        item5->setTextAlignment(Qt::AlignCenter);
        QStandardItem* item6=new QStandardItem();
        item6->setTextAlignment(Qt::AlignCenter);

        item1->setText(tbWcdata.value(1).toString());
        item2->setText(tbWcdata.value(2).toString());
        item3->setText(tbWcdata.value(3).toString());
        item4->setText(tbWcdata.value(4).toString());
        item5->setText(tbWcdata.value(5).toString());
        item6->setText(tbWcdata.value(6).toString());

        QList<QStandardItem*> item;
        item << item1<< item2<< item3<< item4<< item5<< item6;
        pageResult->model->appendRow(item);
        pageResult->tabWcData->setModel(pageResult->model);
    }
    pageResult->tabWcData->setDragEnabled(false);
}

void MainWindow::startTimer()
{
    delShowtimer->start(3000);
}
void MainWindow::stopTimer()
{
    delShowtimer->stop();
}
void MainWindow::showDelAllMsg()
{
    delShowtimer->stop();

    if (dataCount==0)
        return;

    frmMessageBox *msg = new frmMessageBox;
    msg->SetMessage("确定要删除所有的记录?", 1);
    int ret=msg->exec();

    if (ret==1)
    {
        myDB->DelAll();
        showNull();
        dataCount=0;
    }
}

void MainWindow::delWcdata()
{
    QString xh = tbWcxx.value(0).toString();

    frmMessageBox *msg = new frmMessageBox;
    msg->SetMessage("确定要删除此条记录？", 1);

    int ret=msg->exec();

    if (ret==1)
    {
        myDB->delWc(xh);
        dataCount= dataCount - 1;
        tbWcxx=myDB->openWcxx();

        if (dataCount>0)
        {
            tbWcxx.last();
            showWcdata();
        }
        else
            showNull();
    }
}

void MainWindow::showNull()
{
    pageResult->labRecordIndex->setText("");
    pageResult->labRecordSyncMethod->setText("");
    pageResult->labRecordStdInput->setText("");
    pageResult->labRecordDut->setText("");
    pageResult->labRecordStdValue->setText("");
    pageResult->labRecordDate->setText("");
    pageResult->model->clear();
    pageResult->model->setColumnCount(6);
    pageResult->model->setHeaderData(0,Qt::Horizontal,tr("标准百分点"));
    pageResult->model->setHeaderData(1,Qt::Horizontal,tr("被测百分点"));
    pageResult->model->setHeaderData(2,Qt::Horizontal,tr("标准有效值"));
    pageResult->model->setHeaderData(3,Qt::Horizontal,tr("被测有效值"));
    pageResult->model->setHeaderData(4,Qt::Horizontal,tr("比差(%)"));
    pageResult->model->setHeaderData(5,Qt::Horizontal,tr("角差(′)"));
    pageResult->tabWcData->setModel(pageResult->model);
    pageResult->labDataCount->setText(tr("无数据"));
}

void MainWindow::saveWcdata()
{
    static int testSerialNO = 0;

    qDebug()<<"save records";

    // once start is clicked new save cycle will begin
    if(newSaveCycle)
    {
        qDebug()<<"add a new record";

        if ( (testSerialNO = myDB->newTest()) <= 0)
        {
            return;
        }

        qDebug()<<"add new record, xh="<<QString::number( testSerialNO );

        QString tbfs = ui->labSync->text();

        QString primaryValue = ui->labPreV->text();
        primaryValue += ", "+ ui->labPreI->text();

        QString stdInput = ui->labStdV->text() + ", ";
        stdInput += ui->labStdI->text();

        QString dutSelection = ui->labMU->text() + ", " + ui->labMAC->text();

        myDB->addNewRecord(testSerialNO, tbfs, primaryValue, stdInput, dutSelection);

        newSaveCycle = false;
    }

    if(0 == testSerialNO) return;

    //addData2Record(testSerialNO, "电压"，vRMS,vPhase,vDutRMS,vDutPhase,vRatioError,vPhaseError)

    myDB->addData2Record(testSerialNO,"Ua",
                         pageErrorTest->labPhaseAUReal->text(),
                         pageErrorTest->labPhaseAUTest->text(),
                         pageErrorTest->labPhaseAUError->text(),
                         pageErrorTest->labPhaseAUDelay->text());

    myDB->addData2Record(testSerialNO,"Ia",
                         pageErrorTest->labPhaseAIReal->text(),
                         pageErrorTest->labPhaseAITest->text(),
                         pageErrorTest->labPhaseAIError->text(),
                         pageErrorTest->labPhaseAIDelay->text());

    myDB->addData2Record(testSerialNO,"Ub",
                         pageErrorTest->labPhaseBUReal->text(),
                         pageErrorTest->labPhaseBUTest->text(),
                         pageErrorTest->labPhaseBUError->text(),
                         pageErrorTest->labPhaseBUDelay->text());

    myDB->addData2Record(testSerialNO,"Ib",
                         pageErrorTest->labPhaseBIReal->text(),
                         pageErrorTest->labPhaseBITest->text(),
                         pageErrorTest->labPhaseBIError->text(),
                         pageErrorTest->labPhaseBIDelay->text());

    myDB->addData2Record(testSerialNO,"Uc",
                         pageErrorTest->labPhaseCUReal->text(),
                         pageErrorTest->labPhaseCUTest->text(),
                         pageErrorTest->labPhaseCUError->text(),
                         pageErrorTest->labPhaseCUDelay->text());

    myDB->addData2Record(testSerialNO,"Ic",
                         pageErrorTest->labPhaseCIReal->text(),
                         pageErrorTest->labPhaseCITest->text(),
                         pageErrorTest->labPhaseCIError->text(),
                         pageErrorTest->labPhaseCIDelay->text());

    QString s="测试结果已保存，存储序号："+QString::number(testSerialNO);

    showInfo(s);
}

void MainWindow::autoJDError()
{
    qDebug()<<"autoJDError(), btn_test clicked!";

    if (pageAuto->test() == false)
    {
        pageErrorTest->btnStart->setEnabled(true);
        return;
    }
    if ((pageAuto->chkCURR->isChecked() == false) &&  (pageAuto->chkVOLT->isChecked() == false)) return;

    autotestMask->raise();
    autotestMask->show();

    pageErrorTest->extPages->setCurrentIndex(1);

    bool testPointU[5];
    bool testPointI[6];

    QString strU,strI;

    testPointU[0] = pageAuto->chkVOLT_20->isChecked();
    testPointU[1] = pageAuto->chkVOLT_50->isChecked();
    testPointU[2] = pageAuto->chkVOLT_80->isChecked();
    testPointU[3] = pageAuto->chkVOLT_100->isChecked();
    testPointU[4] = pageAuto->chkVOLT_120->isChecked();

    testPointI[0] = false;
    testPointI[1] = pageAuto->chkCURR_5->isChecked();
    testPointI[2] = pageAuto->chkCURR_20->isChecked();
    testPointI[3] = false;
    testPointI[4] = pageAuto->chkCURR_100->isChecked();
    testPointI[5] = pageAuto->chkCURR_120->isChecked();

    for(int i = 0; i < 5; i++)
    {
        if(testPointU[i])
        {
            pageErrorTest->sourcePage->widgetB->funcBtnUList[i+1]->click();

            labAutoTestU->setText("电压百分比 "+pageErrorTest->sourcePage->widgetB->funcBtnUList[i+1]->text());
        }

        if(testPointI[i])
        {
            pageErrorTest->sourcePage->widgetB->funcBtnIList[i+1]->click();

            labAutoTestI->setText(" ,电流百分比 "+pageErrorTest->sourcePage->widgetB->funcBtnIList[i+1]->text());
        }

        ui->btnFunc1_Error->click();

        UaErr = UbErr = UcErr = 0.0;//电压比差
        IaErr = IbErr = IcErr = 0.0;//电流比差
        UaErr_p = UbErr_p = UcErr_p = 0.0;//电压角差
        IaErr_p = IbErr_p = IcErr_p = 0.0;//电流角差

        jingdu_count = 0;

        pageErrorTest->btnStart->setEnabled(false);

        startErrorTest();

        QTime dieTime = QTime::currentTime().addSecs(80);

        while( QTime::currentTime() < dieTime )
        {
            if(autotestMask->isHidden())
            {
                initTestPara();
                return;
            }

            QCoreApplication::processEvents(QEventLoop::AllEvents);
        }

        startErrorTest();

        QTime delayTime = QTime::currentTime().addSecs(3);
        while( QTime::currentTime() < delayTime )
        {
            QCoreApplication::processEvents(QEventLoop::AllEvents);
        }

        labAutoTestCount->setText("");

        if (testPointU[i])
        {
            strU += QString::number(UaErr);
            strU += ";";
            strU += QString::number(UaErr_p);
            strU += ";";
            strU += QString::number(UbErr);
            strU += ";";
            strU += QString::number(UbErr_p);
            strU += ";";
            strU += QString::number(UcErr);
            strU += ";";
            strU += QString::number(UcErr_p);
            strU += ";";
        }
        else
        {
            strU += "/;/;/;/;/;/;";
        }

        if (i == 0 || i == 3) continue;

        if (testPointI[i])
        {
            strI += QString::number(IaErr);
            strI += ";";
            strI += QString::number(IaErr_p);
            strI += ";";
            strI += QString::number(IbErr);
            strI += ";";
            strI += QString::number(IbErr_p);
            strI += ";";
            strI += QString::number(IcErr);
            strI += ";";
            strI += QString::number(IcErr_p);
            strI += ";";
        }
        else
        {
            strI += "/;/;/;/;/;/;";
        }
    }

    if(testPointI[5])
    {
        pageErrorTest->sourcePage->widgetB->funcBtnIList[6]->click();
    }

    startErrorTest();

    QTime dieTime = QTime::currentTime().addSecs(80);

    while( QTime::currentTime() < dieTime )
    {
        if(autotestMask->isHidden())
        {
            initTestPara();
            return;
        }

        QCoreApplication::processEvents(QEventLoop::AllEvents);
    }

    labAutoTestCount->setText("");

    startErrorTest();

    if (testPointI[5])
    {
        strI += QString::number(IaErr);
        strI += ";";
        strI += QString::number(IaErr_p);
        strI += ";";
        strI += QString::number(IbErr);
        strI += ";";
        strI += QString::number(IbErr_p);
        strI += ";";
        strI += QString::number(IcErr);
        strI += ";";
        strI += QString::number(IcErr_p);
        strI += ";";
    }
    else
    {
        strI += "/;/;/;/;/;/;";
    }

    pageAuto->setDataVOLT(strU);
    pageAuto->setDataCURR(strI);
    pageAuto->btnTest->setEnabled(true);

    ui->btnFunc5->click();

    autotestMask->hide();
}

void MainWindow::stopAuto()
{
    pageAuto->btnTest->click();

    ui->btnFunc5->click();
}
